예제 #1
0
파일: randomquote.py 프로젝트: situx/tuxbot
def quoteofperson(bot,trigger):
    """Retrieves a quote from the person given as parameter"""
    result=wikiquote.quotes(trigger.group(2))
    if"NoSuchPageException" in result:
        bot.say("Not quote for person "+trigger.group(2)+" found!")
    else:
        bot.say(str(random.choice(wikiquote.quotes(trigger.group(2)))))
예제 #2
0
def generate_random_quote():
    quotes = []  #create empty quotes list
    for t in wikiquote.random_titles():
        quotes.append(wikiquote.quotes(t))
    quotes.append(generate_asip_quote())
    quotes.append(wikiquote.quotes('King of the Hill (season 2)'))
    return quotes
예제 #3
0
def do_quote():
    while True:
        quote_list = []
        print(
            "\n\nHello wise internet user, so you want to brew some good quotes!"
            "Choose the options we can serve u now:\n"
            "1.  Quote of the Day\n"
            "2.  Search the keyword you wish to see quotes on ( a movie, an author, anything)\n"
            "3.  Show some random titles to search quotes on\n"
            "4.  Just show some random quotes ( in case u r in a hurry)\n")

        choice = int(input("Enter your Choice: "))
        print()
        if choice == 1:
            qOtD = []
            qOtD = list(wikiquote.quote_of_the_day())
            print("\n{} \n \t\t\t --{}".format(qOtD[0], qOtD[1]))
            break

        elif choice == 2:
            search_result = []
            srch_txt = input("Enter the keyword you wish to search: ")
            search_result = list(wikiquote.search(srch_txt))
            if search_result:
                print("\nEnter the item number you wish to see a quote on: \n")
                for x, item in enumerate(search_result, 1):
                    print("{}.    {}".format(x, item))
                srch_choice = int(input())
                srch_strng = search_result[srch_choice - 1]
                quote_list = list(wikiquote.quotes(srch_strng, max_quotes=5))
                print()
                for i, item in enumerate(quote_list, 1):
                    print("{}.   {}\n".format(i, item))
                break

            else:
                print("no quotes on that! try again.....")

        elif choice == 3:
            rand_ttls = list(wikiquote.random_titles(max_titles=5))
            print("\nEnter the item number you wish to see a quote on: \n")
            for i, item in enumerate(rand_ttls, 1):
                print("{}.  {}".format(i, item))
            srch_choice = int(input())
            srch_strng = rand_ttls[srch_choice - 1]
            quote_list = list(wikiquote.quotes(srch_strng, max_quotes=5))
            for m, item in enumerate(quote_list, 1):
                print("{}.  {}\n".format(m, item))
            break

        elif choice == 4:
            rand_ttls = list(wikiquote.random_titles(max_titles=5))
            rnd_str = random.choice(rand_ttls)
            try:
                print(random.choice(wikiquote.quotes(rnd_str)))
                break
            except UnboundLocalError:
                print(
                    "[!] Sorry, some technical glitch occured, please try again!"
                )
def quotes_jessica(a):
	if str(a) == "Inspire" or str(a) == "inspire":
		y = ['life','happiness','success','love','family','dedication','work','hard work','friends','lucky']
		z = random.choice(y)
		print( wikiquote.quotes(z,max_quotes = 1) )
		pyt.say( wikiquote.quotes(z,max_quotes = 1) )

	elif str(a) == "quotes" or str(a) == "Quotes":
		pyt.say("Search quote about:")
		y = input(">>>")
		print( wikiquote.quotes(y,max_quotes = 1) )
		pyt.say( wikiquote.quotes(y,max_quotes = 1) )
	
	
	elif str(a) == "Quote" or str(a) == "quote" :	
		print( wikiquote.quote_of_the_day())
		pyt.say( wikiquote.quote_of_the_day() )

	#elif str(a) == "Random" or str(a) == "random":
	#	y = ['life','happiness','success','love','family','dedication','work','hard work','friends','lucky']
	#	z = random.choice(y)
	#	print( wikiquote.quotes(z,max_quotes = 1) )
	#	pyt.say( wikiquote.quotes(z,max_quotes = 1) )
	else:
		
		pyt.say("Quotes not found")
예제 #5
0
 def _is_in_site(self, row):
     name = row[16]
     try:
         wikiquote.quotes(name)
     except Exception as e:
         if e.__class__.__name__ != 'NoSuchPageException':
             print('{0}: {1}'.format(name, e))
         return False
     return name
예제 #6
0
    async def _quote(self, ctx, *query):
        if ' '.join(query):
            res = wikiquote.quotes(random.choice(
                wikiquote.search(' '.join(query).strip())))
            if not res:
                return await ctx.reply(f'No quotes from {" ".join(query).strip()}')
            return await ctx.reply(f'```\n{res[0]}\n~{" ".join(query).strip()}```')

        def check(author):
            def inner_check(message):
                return message.author == author
            return inner_check

        try:
            await ctx.reply("Would you like a random quote? `Yes/No`\nYou have 30 seconds to respond")
            answer = await self.bot.wait_for('message', check=check, timeout=30)
        except asyncio.TimeoutError:
            return await ctx.reply("You took too long, stupid slow human")

        if "y" in answer.content.lower():
            author = random.choice(wikiquote.random_titles())
            res = random.choice(wikiquote.quotes(author))
            return await ctx.reply(f'```\n{res}\n~{author}```')
        elif not "n" in answer.content.lower():
            return await ctx.reply("Invalid choice!")

        try:
            await ctx.reply("What would you like to search for? \nYou have 30 seconds to respond")
            answer = await self.bot.wait_for('message', check=check, timeout=30)
        except asyncio.TimeoutError:
            return await ctx.reply("You took too long, stupid slow human")

        search_res = wikiquote.search(answer.content.strip())
        res = ""
        for i in search_res:
            res += f'{search_res.index(i) + 1}. {i}\n'

        def check2(author):
            def inner_check(message):
                if message.author != author:
                    return False
                try:
                    int(message.content)
                    return True
                except ValueError:
                    return False
            return inner_check

        try:
            await ctx.reply(f'(Respond with the number. You have 30 seconds)\nGet random quote from topic:\n```\n{res}```')
            answer = await self.bot.wait_for('message', check=check2, timeout=30)
        except asyncio.TimeoutError:
            return await ctx.reply("You took too long, stupid slow human")

        await ctx.reply(f'Random result from topic: `{search_res[int(answer.content) - 1]}`'
                        f'\n\n```\n{random.choice(wikiquote.quotes(search_res[int(answer.content) - 1]))}```')
예제 #7
0
async def quote(ctx, arg):
    #    try:
    response = random.choice(wikiquote.quotes(arg))
    #except wikiquote.DisambiguationPageException as e:
    #  s = random.choice(e.options)
    #  response = wikiquote.quotes(s)
    await ctx.send(response)
예제 #8
0
    async def quote(self, ctx, autor: str = ''):
        """Manda una frase de un filosofo"""
        autores = [
            'Séneca', 'El_arte_de_la_guerra', 'Carlos_Menem', 'Epicteto',
            'Sócrates', 'Stephen_King', 'Bruce_Lee', 'Diego_Armando_Maradona',
            'Ricardo_Iorio', 'Naruto:_Shippūden', 'Nach', 'Jorge_Luis_Borges',
            'Oscar_Wilde', 'Platón', 'Francisco_de_Quevedo', 'Soledad',
            'Domingo_Cavallo', 'Friedrich_Nietzsche', 'Sexualidad',
            'José_Mujica', 'Milton_Friedman', 'Jostein_Gaarder',
            'Jesús_de_Nazaret', 'Ateísmo', 'Charles_Darwin', 'Stephen_Hawking',
            'Gabriel_García_Márquez', 'Sigmund_Freud',
            'El_guardián_entre_el_centeno', 'Charles_Bukowski', 'Confucio',
            'Dale_Carnegie'
        ]

        if autor == '':
            autor = random.choice(autores)

        frases = wikiquote.quotes(autor, lang='es', max_quotes=0)

        print("Autor: {} Cant: {}".format(str(autor), len(frases)))

        # Devuelve True si es mala
        def fail_condition(msj):
            prohibido = ['isbn', 'Obras de don Francisco', 'Reunido en Oviedo']
            return any(word in msj.lower() for word in prohibido)

        choice = random.choice(frases)
        while fail_condition(choice):
            choice = random.choice(frases)

        await ctx.send(choice)
예제 #9
0
 def getRandomQuote(self,
                    titles,
                    mostRelevant=False,
                    length=4,
                    filterYear=True):
     quote = None
     quotes = None
     match = None
     counter = 0
     max_sentences = length
     while quote is None or len(quote.split('.')) > max_sentences:
         counter += 1
         if not mostRelevant: title = random.choice(titles)
         else: title = titles[0]
         try:
             quotes = wikiquote.quotes(title, lang=self.wikilang)
         except wikiquote.utils.DisambiguationPageException:
             quotes = None
         if quotes and quotes != []:
             quote = random.choice(quotes)
             if filterYear: match = re.match('.*([1-3][0-9]{3})', quote)
             if match: quote = None
             for word in self.exclude_list:
                 if quote and word in quote: quote = None
         if counter > 5: quote = ''
     return quote, title
예제 #10
0
def inlinequery(bot, update):
    query = update.inline_query.query
    if query != "":

        author = wikiquote.search(query)[0]
        try:
            quotes = wikiquote.quotes(author, max_quotes=15)
            results = list()

            logging.debug(author)
            for quote in quotes:
                results.append(
                    InlineQueryResultArticle(
                        id=uuid4(),
                        title=author,
                        description=quote,
                        input_message_content=InputTextMessageContent(
                            '*{}:*\n{}'.format(author, quote),
                            parse_mode=ParseMode.MARKDOWN)))
        except wikiquote.utils.DisambiguationPageException:
            results = [
                InlineQueryResultArticle(
                    id=uuid4(),
                    title=author + ' gives disambiguation',
                    description='Sorry!',
                    input_message_content=InputTextMessageContent(
                        author + ' gives a disambiguation page :('))
            ]

        bot.answer_inline_query(update.inline_query.id, results)
예제 #11
0
def home(request):
    all_img = [
        "https://cdn.wallpapersafari.com/21/3/FDXab2.jpg",
        "https://www.wallpaperflare.com/static/821/889/92/blurred-motion-blur-colorful-landscape-wallpaper.jpg",
        "https://million-wallpapers.com/wallpapers/3/59/462865831916145.jpg",
        "https://wallpaperaccess.com/full/2898150.jpg",
        "https://img3.goodfon.com/wallpaper/nbig/4/4d/dusk-silhouettes-twilight-lights-hill.jpg",
        "https://papers.co/wallpaper/papers.co-oe87-nature-mountain-blur-29-wallpaper.jpg",
        "https://hdwallpaperim.com/wp-content/uploads/2017/08/25/462045-blurred-sky-nature-748x421.jpg",
        "https://wallup.net/wp-content/uploads/2015/12/65322-landscape-nature-mountain-sunset-sunrise-sunlight-blurred-Nepal-Himalayas-climbing-rock.jpg"
    ]

    quotes = Info()
    rimg = rImages()
    rfonts = Rfonts()

    rand_fonts = random.choice(["Mali", "Rajdhani", "Raleway", "Acme"])

    rand_persons = random.choice([
        "Linus Torvalds", "Bill Gates", "Walt Disney", "Albert Einstein",
        "Walt Disney", "William Shakespeare", "Elon Musk"
    ])

    quotes.quotes = random.choice(wikiquote.quotes(str(rand_persons)))
    quotes.name = rand_persons

    rimg.urls = random.choice(all_img)

    rfonts.name = rand_fonts

    return render(request, 'home.html', {
        'quotes': quotes,
        'rimg': rimg,
        'rfonts': rfonts
    })
예제 #12
0
 def search(self, sc, message):
     search = wikiquote.search(message)
     if search:
         quotes = wikiquote.quotes(search[0], max_quotes=1)
         for quote in quotes:
             self.send_message(sc, search[0] + ": " + quote)
     else:
         self.send_message(sc, "That's not a thing")
예제 #13
0
def get_quotes_from_author(quotes, author):
    author_quotes = wikiquote.quotes(author)
    tweets = ["{0} - {1}".format(quote, author) for quote in author_quotes]

    for tweet in tweets:
        quotes.append(tweet)

    return quotes
예제 #14
0
    def get(self, request, *args, **kwargs):
        form = self.form_class()

        quote = random.choice(wikiquote.quotes('Proverbi_italiani', lang='it'))
        return render(request, self.template_name, {
            'form': form,
            'quote': quote
        })
예제 #15
0
def get_quote(word):
    try:
        search = wq.search(word)[0]
        quote = wq.quotes(search, lang="en")
        unchecked = random.choice(quote)
        final_step = translate(unchecked)
        return final_step
    except:
        return "Quote not found"
예제 #16
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)
예제 #17
0
 def get_selection(self, author):
     try:
         return wikiquote.quotes(author)
     except wikiquote.utils.NoSuchPageException:
         msg = MISSING_AUTHOR.format(author=author)
         raise RetryException(msg, author)
     except wikiquote.utils.DisambiguationPageException:
         msg = DISAMB_AUTHOR.format(author=author)
         raise RetryException(msg, author)
예제 #18
0
 def tellMeMore(self, sc, message):
     search = wikiquote.search(message)
     if search:
         quotes = wikiquote.quotes(search[0], max_quotes=10000)
         for quote in quotes:
             if message.lower() in quote.lower():
                 self.send_message(sc, search[0] + ": " + quote)
     else:
         self.send_message(sc, "That's not a thing")
예제 #19
0
def test():
	j = 0
	for i in range(len(GENIUS)):
		quotes = wikiquote.quotes(GENIUS[i], "en")
		for quote in quotes:
			if len(quote)<= MAX_QUOTES_LENGTH:
				j+=1
		print("%s passed", i)
	print("Total available citations = %s", j)
예제 #20
0
파일: hype.py 프로젝트: rohan166/cerealbot
def get_quote():
    while True:
        try:
            titles = wq.random_titles(max_titles=1)
            print("found title: ", titles)
            quote = wq.quotes(titles[0])[0]
            return quote
        except:
            continue
예제 #21
0
def confronto(quotes):
    possibilities = []
    possibilities.extend([random.choice(wikiquote.quotes('The_Fellowship_of_the_Ring')),
                         random.choice(wikiquote.quotes('The_Two_Towers')),
                         random.choice(wikiquote.quotes('The_Return_of_the_King'))])
    quote = random.choice(possibilities)
    if quote not in quotes:
        if len(quote)<141 and quote is not None:
            quotes.append(quote)
            print(quote)
            with open('database.json', 'w') as data_file:
                json.dump(quotes, data_file)
            print('*************')
            print(quotes)
            print('*************')
        else:
            confronto(quotes)
    else:
        confronto(quotes)
예제 #22
0
def random_quotes():
	form = RandomQuotesForm()
	if request.method == 'POST':
		word = form.word.data
		raw_data = []
		quotes = wikiquote.quotes(word.casefold())
		for quote in quotes:
			raw_data.append(quote)
		return render_template('random_quotes.html', form = form, raw_data = raw_data)
	return render_template('random_quotes.html', form = form)
예제 #23
0
def get_quote():
    titles = wikiquote.random_titles()
    for title in titles:
        lower_title = title.lower()
        print('trying title', title)
        quotes = None
        if title.startswith('List of'):
            continue
        if any(w in lower_title for w in bad_titles):
            continue
        try:
            quotes = wikiquote.quotes(title, max_quotes=1000)
        except (NoSuchPageException, DisambiguationPageException):
            pass

        if not quotes:
            continue

        quotes = [q for q in quotes if len(q) < 140]

        random.shuffle(quotes)
        for quote in quotes:
            # Don't use lines of dialogue
            if '\n' in quote:
                continue

            # Not interested in brackets
            if '[' in quote:
                continue

            # Assume this is a quote from a character and not a person
            if ':' in quote[:20]:
                continue

            # Assume this is an external link and not a quote
            if lower_title in quote.lower():
                continue

            # Strip enclosing quotes
            if quote[0] == quote[-1] and quote[0] in ('"', "'"):
                quote = quote[1:-2]

            words = quote.split()
            if len(words) < 4:
                continue
            if any(w in quote.lower() for w in bad_words):
                continue
            new_quote = ' \U0001f44f '.join(words)
            if len(new_quote) <= 140:
                print('Chosen quote from', title)
                return new_quote

    # Couldn't find matching quotes
    return None
예제 #24
0
    def quoteMe(self, sc):

        self.rand = wikiquote.random_titles(max_titles=1)[0]
        quotes = wikiquote.quotes(self.rand, max_quotes=1)
        message = ""
        for quote in quotes:
            if len(quote) < 80:
                message = quote
        if message:
            self.send_message(sc, message + ", Who am I?")
        else:
            self.send_message(sc, quotes[0] + ", Who am I?")
예제 #25
0
def confronto(quotes):
    possibilities = []
    possibilities.extend([
        random.choice(wikiquote.quotes('The_Fellowship_of_the_Ring')),
        random.choice(wikiquote.quotes('The_Two_Towers')),
        random.choice(wikiquote.quotes('The_Return_of_the_King'))
    ])
    quote = random.choice(possibilities)
    if quote not in quotes:
        if len(quote) < 141 and quote is not None:
            quotes.append(quote)
            print(quote)
            with open('database.json', 'w') as data_file:
                json.dump(quotes, data_file)
            print('*************')
            print(quotes)
            print('*************')
        else:
            confronto(quotes)
    else:
        confronto(quotes)
예제 #26
0
def next_round():
    nextx = session.attributes['search_item']
    nextx = nextx.title()
    try:
        quotes = wikiquote.quotes(nextx)       
    except wikiquote.utils.DisambiguationPageException:
        nextx = wikiquote.search(nextx)[0]
        quotes = wikiquote.quotes(nextx)
    except wikiquote.utils.NoSuchPageException:
        for search in wikiquote.search(nextx):
            if nextx.lower() in search.lower():
                quotes = wikiquote.quotes(search)
                break
        else:
            # raise wikiquote.utils.NoSuchPageException('No pages matched' + search_item)
            return question("Sorry, I can't find proper quotes, please try a more specific word.")
    nquotes = random.choice(quotes)
    nquote_msg = 'From {}, {}'.format(nextx, nquotes)
    reprompt_msg = 'Would you like one more quote?'
    return question(nquote_msg) \
          .reprompt(reprompt_msg)
예제 #27
0
def download_quotes(person, file):
    with open(file, 'a') as f:
        quotes = wikiquote.quotes(person, max_quotes=200)
        for quote in quotes:
            if quote.find(":") != -1:
                f.write(quote + '\n')
            else:
                quote = quote.split(":")
                names = [name for name in person.split()]
                i = 0
                for i in range(len(quote)):
                    if quote[i] in names:
                        f.write(quote[i + 1] + '\n')
예제 #28
0
파일: Bot.py 프로젝트: crappyoats/quote_bot
    def _find_quotes(self, term):
        """find quotes for search terms in topic dict. filters for less than 
        120 characters"""
        try:
            tweetable = []
            quotes = wikiquote.quotes(term)
            for each in quotes:
                if len(each) < 121:
                    tweetable += [each]

            return tweetable
        except:
            pass                    
예제 #29
0
def wisdom_quotes(search_item):
    search_item = search_item.title()
    try:
        quotes = wikiquote.quotes(search_item)       
    except wikiquote.utils.DisambiguationPageException:
        search_item = wikiquote.search(search_item)[0]
        quotes = wikiquote.quotes(search_item)
    except wikiquote.utils.NoSuchPageException:
        for search in wikiquote.search(search_item):
            if search_item.lower() in search.lower():
                quotes = wikiquote.quotes(search)
                break
        else:
            # raise wikiquote.utils.NoSuchPageException('No pages matched' + search_item)
            return question("Sorry, I can't find proper quotes, please try a more specific word.")
    wquotes = random.choice(quotes)
    wquote_msg = 'From {}, {}'.format(search_item, wquotes)
    reprompt_msg = 'Would you like one more quote?'
    session.attributes['search_item'] = search_item
    session.attributes['reply'] = wquote_msg
    return question(wquote_msg) \
          .reprompt(reprompt_msg)
예제 #30
0
def find_quotes():
    i = 0
    first = ""
    second = ""
    third = ""
    dict = {}
    while i < 3:
        quote_index = wikiquote.random_titles()
        try:
            title = random.choice(quote_index)
            quotes = wikiquote.quotes(title)
            if not quotes:
                raise EmptyException
        except DisambiguationPageException:
            quotes = wikiquote.qotd()
            title = quotes[1]
        except EmptyException:
            quotes = wikiquote.qotd()
            title = quotes[1]
        syl = 0
        line = ""
        for word in quotes[0].split(" "):
            if "." in word:
                syl += sylco(word)
                line += word
                line += " "
                break
            syl += sylco(word)
            line += word
            line += " "

        if not first and syl is 5:
            first = line
            dict[first] = title
            i += 1
        elif not second and syl is 7:
            second = line
            dict[second] = title
            i += 1
        elif not third and syl is 5:
            third = line
            dict[third] = title
            i += 1
    # save_path = "C:/Users/natha/Documents/Personal Projects/quotes/Haikus"
    # file = os.path.join(save_path, dict[first]+".txt")
    # f = open(file, "w")
    # f.write('\n' + "Haiku:" + '\n' + first + '\n' + second + '\n' + third + '\n')
    # f.write('\n' + "Authors:" + '\n' + dict[first] + '\n' + dict[second] + '\n' + dict[third])
    content = '\n' + "Haiku:" + '\n' + first + '\n' + second + '\n' + third + '\n'
    content += '\n' + "Haiku:" + '\n' + first + '\n' + second + '\n' + third + '\n'
    return dict[first], content
예제 #31
0
def qfind(query):
    Authorlist = findtitles(query=query)
    if Authorlist == []:
        return ["NoAuthorFound", wikiquote.random_titles(max_titles=7)]
    else:
        Authorlist.sort()
        for i in Authorlist:
            if query.lower() == i.lower():
                qt = ranlist(i)
                if qt == []:
                    Authorlist.remove(i)
                    continue
                else:
                    Authorlist.remove(i)
                    return ["Success", choice(qt), i, Authorlist]
        for i in Authorlist:
            if query.lower() in i.lower() or i.lower() in query.lower():
                qt = ranlist(i)
                if qt == []:
                    Authorlist.remove(i)
                    continue
                else:
                    Authorlist.remove(i)
                    return ["Success", choice(qt), i, Authorlist]
        Quotelist = []
        Resultlist = []
        for i in Authorlist:
            try:
                a = wikiquotes.get_quotes(i, "english")
            except:
                pass
            else:
                Quotelist = a
                del a
            try:
                c = wikiquote.quotes(i, max_quotes=5)
            except:
                c = []
            for k in c:
                if k not in Quotelist:
                    Quotelist.append(k)
            for j in Quotelist:
                if query.lower() in j.lower():
                    Resultlist.append([j, i])
        if Resultlist != []:
            Resultlist.sort()
            Quote = choice(Resultlist)
            Authorlist.remove(Quote[1])
            return ["Success", Quote[0], Quote[1], Authorlist]
        else:
            return ["NoQuoteFound", Authorlist]
예제 #32
0
def ranlist(title):
    try:
        a = [wikiquotes.random_quote(title, "english")]
    except:
        a = []
    try:
        b = wikiquote.quotes(title, max_quotes=1)
    except:
        b = []
    Newlist = a + b
    for i in blacklist:
        if i in Newlist:
            Newlist.remove(i)
    return Newlist
예제 #33
0
def next_round():
    nextx = session.attributes['search_item']
    nextx = nextx.title()
    try:
        quotes = wikiquote.quotes(nextx)
    except wikiquote.utils.DisambiguationPageException:
        nextx = wikiquote.search(nextx)[0]
        quotes = wikiquote.quotes(nextx)
    except wikiquote.utils.NoSuchPageException:
        for search in wikiquote.search(nextx):
            if nextx.lower() in search.lower():
                quotes = wikiquote.quotes(search)
                break
        else:
            # raise wikiquote.utils.NoSuchPageException('No pages matched' + search_item)
            return question(
                "Sorry, I can't find proper quotes, please try a more specific word."
            )
    nquotes = random.choice(quotes)
    nquote_msg = 'From {}, {}'.format(nextx, nquotes)
    reprompt_msg = 'Would you like one more quote?'
    return question(nquote_msg) \
          .reprompt(reprompt_msg)
예제 #34
0
def wisdom_quotes(search_item):
    search_item = search_item.title()
    try:
        quotes = wikiquote.quotes(search_item)
    except wikiquote.utils.DisambiguationPageException:
        search_item = wikiquote.search(search_item)[0]
        quotes = wikiquote.quotes(search_item)
    except wikiquote.utils.NoSuchPageException:
        for search in wikiquote.search(search_item):
            if search_item.lower() in search.lower():
                quotes = wikiquote.quotes(search)
                break
        else:
            # raise wikiquote.utils.NoSuchPageException('No pages matched' + search_item)
            return question(
                "Sorry, I can't find proper quotes, please try a more specific word."
            )
    wquotes = random.choice(quotes)
    wquote_msg = 'From {}, {}'.format(search_item, wquotes)
    reprompt_msg = 'Would you like one more quote?'
    session.attributes['search_item'] = search_item
    session.attributes['reply'] = wquote_msg
    return question(wquote_msg) \
          .reprompt(reprompt_msg)
예제 #35
0
def get_random(ctx, title):
    titles = (
        random_titles(lang=ctx.obj["lang"])
        if not title
        else search(title, lang=ctx.obj["lang"])
    )
    if titles:
        try:
            quote = random.choice(quotes(titles[0], lang=ctx.obj["lang"]))
            print(pretty(quote, titles[0]))
        except DisambiguationPageException:
            return 2
        except NoSuchPageException:
            return 1
    return 0
예제 #36
0
 def quote_cmd(cls, ctx):
     chat = cls.bot.get_chat(ctx.msg)
     if ctx.text:
         pages = wq.search(ctx.text, lang=cls.LANG)
         if pages:
             author = pages[0]
             quote = '"%s"\n\n― %s' % (random.choice(
                 wq.quotes(author, max_quotes=100, lang=cls.LANG)), author)
         else:
             quote = _('No quote found for: {}').format(ctx.text)
         chat.send_text(quote)
     else:
         quote, author = wq.quote_of_the_day(lang=cls.LANG)
         quote = '"{}"\n\n― {}'.format(quote, author)
         chat.send_text(quote)
예제 #37
0
def main():
    if len(argv) > 1:
        print(hypify(" ".join(argv[1:])))
    else:
        while True:
            try:
                titles = wq.random_titles(max_titles=1)
                print("found title: ", titles)
                quote= wq.quotes(titles[0])[0]
            except:
                continue
            break
        print("got quote:\n", quote)
        hype = hypify(quote)
        while hype is None:
            hype = hypify(quote)
        print(hype)
예제 #38
0
    async def quote(self, choice):
        """Generating a random quote or get the quote of the day.

        **Dependencies**: pip install wikiquote

        Keyword arguments:
        choice -- either 'QOTD' (Quote of the day) or 'R' (Random)

        """

        if choice.upper() == 'QOTD':
            quote = wikiquote.quote_of_the_day()
            await self.bot.say("'{}' -- {}".format(quote[0], quote[1]))
        elif choice.upper() == 'R':
            while True:
                authors = wikiquote.random_titles(max_titles=5)
                random_author = random.choice(authors)
                if random_author.isdigit():
                    continue
                random_quote = random.choice(wikiquote.quotes(random_author))
                await self.bot.say("'{}' -- {}"
                                   .format(random_quote,
                                           random_author))
                break
예제 #39
0
 def test_normal_quotes(self):
     quotes = wikiquote.quotes('The Matrix (film)')
     self.assertTrue(len(quotes) > 0)
예제 #40
0
 def test_normal_quotes(self):
     for lang in wikiquote.langs.SUPPORTED_LANGUAGES:
         quotes = wikiquote.quotes('Barack Obama', lang=lang)
         self.assertTrue(len(quotes) > 0)
예제 #41
0
 def test_max_quotes(self):
     quotes = wikiquote.quotes('The Matrix (film)', max_quotes = 8)
     self.assertEqual(len(quotes), 8)
예제 #42
0
 def test_max_quotes_and_lang(self):
     quotes = wikiquote.quotes('Matrix', lang='fr', max_quotes = 8)
     self.assertEqual(len(quotes), 8)
access_token_secret = "" """

# authenticating twitter consumer key
auth = tweepy.OAuthHandler(config['consumer_key'], config['consumer_secret'])
auth.set_access_token(config['access_token'], config['access_token_secret'])

# create twitter object
api = tweepy.API(auth)

# get WOEID for zurich
zurich = api.trends_closest(47.3,8.5)
zID = zurich[0]['woeid']

# get current trend hashtags
trendsZ = api.trends_place(zID)

for trendsInZueri in trendsZ[0]['trends']:
	hashTag = trendsInZueri['name'].replace('#','')
	try: 
		searchQuote = wikiquote.search(hashTag)[0]
		randomComment = random.choice(wikiquote.quotes(searchQuote))
		randomComment = randomComment + ' #' + hashTag
		print "sending out tweet: " + randomComment
		api.update_status(randomComment)
		time.sleep(30)
	except:
		print "tweeting failed ... next try for hashtag" + hashTag
		continue

	print randomComment
	print "-----"
예제 #44
0
 def test_lang_quotes(self):
     quotes = wikiquote.quotes('Matrix', lang='fr')
     self.assertTrue(len(quotes) > 0)
import wikiquote
import json
from oauth2client.client import SignedJwtAssertionCredentials
import gspread

json_key = json.load(open("../Weekly Reports-bd2b424c9654.json"))
scope = ["https://spreadsheets.google.com/feeds"]
credentials = SignedJwtAssertionCredentials(json_key["client_email"], bytes(json_key["private_key"], "UTF-8"), scope)
gc = gspread.authorize(credentials)
wks = gc.open_by_key("15vnTQwm68NnE6CaFpUMfQkKO0w2ab98spE2MuYvkAwI").worksheet("Nonfiction Classic")
i = 1
quotes = []
while i <= 100:
    try:
        a = wikiquote.quotes(wks.cell(i, 1).value, max_quotes=5000)
        print(a)
        quotes.append(a)
        i += 1
    except:
        i += 1
i = 0
with open("quotes5.csv", "w") as out_file:
    for row in quotes:
        for q in row:
            i += 1
            print(q, file=out_file)