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]))}```')
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)
def search(query): """Search wikiquotes for a query.""" results = wikiquote.search(query) click.echo(click.style("Found {} results:".format(len(results)), bold=True)) for result in results: click.echo(result)
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 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)
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")
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"
def search_topic(self, topic = "computer science"): """runs wikiquote search. adds search terms to topics list. default search term is 'computer science'. returns list of possible searches""" try: topics = wikiquote.search(topic) return topics except: pass
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")
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)
def handle_specific_quote_intent(self, message): subject = message.data.get('subject') results = wikiquote.search(subject, lang=self.wikilang) if len(results) == 0: self.speak_dialog("notfound", {'subject': subject}) else: quote, title = self.getRandomQuote(results, mostRelevant=True, length=10, filterYear=False) if quote == '': self.speak_dialog("notfound", {'subject': subject}) else: self.speak(quote + ' (' + title + ')')
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)
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)
def findtitles(query): List = [] try: a = wikiquotes.search(query, "english") except: pass else: List = a del a for i in wikiquote.search(query): if i not in List: List.append(i) return List
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)
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
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)
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)
def search(bot, update, args): lang, terms = lang_and_terms(args) if not terms: update.message.reply_text('Usage: /search <terms>') return try: results = wikiquote.search(' '.join(terms), lang=lang) if not results: update.message.reply_text('No results found.') else: reply = 'Results:\n' for result in results: reply += ' - ' + result + '\n' update.message.reply_text(reply) except: update.message.reply_text('An error occured when searching Wikiquote.org.')
def get_quote(name): persons = wikiquote.search(name) random_quote = random.choice(wikiquote.quotes(persons[0])) return random_quote
def test_search(self): results = wikiquote.search('Matrix') self.assertTrue(len(results) > 0)
def test_empty_search(self): results = wikiquote.search('') self.assertEqual(results, [])
def test_search(self): for lang in wikiquote.supported_languages(): results = wikiquote.search("Matrix", lang=lang) self.assertTrue(len(results) > 0)
def test_unsupported_lang(self): with self.assertRaisesRegex(wikiquote.UnsupportedLanguageException, "Unsupported language: foobar"): wikiquote.search("test", lang="foobar")
def search(requested): return wikiquote.search(requested)
def test_search(self): for lang in wikiquote.langs.SUPPORTED_LANGUAGES: results = wikiquote.search('Matrix', lang=lang) self.assertTrue(len(results) > 0)
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 "-----"
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)) print() quotes = wikiquote.quotes(results[0], lang=lang, max_quotes=10) if quotes: for quote in quotes: if len(quote) > MAX_QUOTE_LEN: quote = quote[:MAX_QUOTE_LEN] + '...' print(' - {}'.format(quote)) else: print('NO QUOTES!')