def run(self):
while True:
msg = self.queue_in.get() # get() is blocking
match = re.search(r'^(?:/|!)wiki (.*)$', msg.get_text().lower())
if match:
reply = ""
try:
related_entries = wikipedia.search(match.group(1))
w = wikipedia.page(match.group(1))
reply1 = "*{}*\n".format(w.title)
reply2 = "{}\n".format(w.summary)
reply3 = "\n*related topics*:\n- {}".format("\n- ".join(related_entries))
if len(reply1+reply2+reply3)>4096:
reply = reply1 + reply2[:4092-len(reply1)-len(reply3)]+"...\n" + reply3 # shortening to 4096 characters
else:
reply = reply1+reply2+reply3
except wikipedia.DisambiguationError as e:
related_entries = str(e).split(":",1)[1].split("\n")[1:]
reply = "This was too inspecific. Choose one from these:\n- {}".format("\n- ".join(related_entries))
except:
reply = "No matches returned for this request."
if reply:
self.bot.sendMessage(msg.get_chat_id(), reply, parse_mode="Markdown")
python类DisambiguationError()的实例源码
def wikipedia(cmd, message, args):
if args:
try:
summary_task = functools.partial(wiki.page, ' '.join(args).lower())
with ThreadPoolExecutor() as threads:
page = await cmd.bot.loop.run_in_executor(threads, summary_task)
response = discord.Embed(color=0xF9F9F9)
response.set_author(
name=f'Wikipedia: {page.title}',
url=page.url,
icon_url='https://upload.wikimedia.org/wikipedia/commons/6/6e/Wikipedia_logo_silver.png'
)
response.description = f'{page.summary[:800]}...'
except wiki.PageError:
response = discord.Embed(color=0x696969, title='?? No results.')
except wiki.DisambiguationError:
response = discord.Embed(color=0xBE1931, title='? Search too broad, please be more specific.')
else:
response = discord.Embed(color=0xBE1931, title='? Nothing inputted.')
await message.channel.send(None, embed=response)
def wikipedia(cmd, message, args):
if args:
q = ' '.join(args).lower()
try:
result = wp.summary(q)
if len(result) >= 650:
result = result[:650] + '...'
response = discord.Embed(color=0xF9F9F9)
response.add_field(name=f'?? Wikipedia: `{q.upper()}`', value=result)
except wp.PageError:
response = discord.Embed(color=0x696969, title='?? No results.')
except wp.DisambiguationError:
response = discord.Embed(color=0xBE1931, title='? Search too broad, please be more specific.')
else:
response = discord.Embed(color=0xBE1931, title='? Nothing inputted.')
await message.channel.send(None, embed=response)
def get_gkg(query):
try:
s = _wk.summary(query, sentences = 5)
for x in _findall("\(.*\)", s):
s = s.replace(x, "")
return s
except _wk.DisambiguationError, e:
return False
def wikipedia_parser(ctx, message):
"""
Returns a wikipedia definition
:param ctx:
:param message:
:return:
"""
try:
querry = message.content[6:]
search = wikipedia.summary(str(querry), sentences=4)
await ctx.send_message(message.channel, "```{}```".format(search))
except wikipedia.DisambiguationError as e:
length = len(e.options)
if length == 1:
await ctx.send_message(message.channel, "Did you mean? `{}`".format(e.options[0]))
elif length == 2:
await ctx.send_message(message.channel, "Did you mean? `{}` or `{}`"
.format(e.options[0], e.options[1]))
else:
await ctx.send_message(message.channel,
"Disambiguation in you query. It can mean `{}`, `{}` and {} more."
.format(e.options[0], e.options[1], str(length)))
except wikipedia.PageError:
await ctx.send_message(message.channel, "No pages matched your querry :cry:")
except wikipedia.HTTPTimeoutError:
await ctx.send_message(message.channel, "Hey there, slow down you searches for a bit!")
except wikipedia.RedirectError:
await ctx.send_message(message.channel,
"Error: page title unexpectedly resolves to a redirect. "
"Please re-check your query.")
except wikipedia.WikipediaException:
await ctx.send_message(message.channel, "Error: The search parameter must be set.")
def ask_wikipedia(self, definition):
'''
Ask Wikipedia for the definition.
:param definition:
:return:
'''
# TODO: this method should run in a separate process, asynchronously
is_exact = False
out = []
if not wikipedia:
return is_exact, out
page_titles = wikipedia.search(definition)
page = None
if page_titles:
for page_title in page_titles:
if page_title.lower() == definition:
try:
page = wikipedia.page(page_title)
is_exact = True
except DisambiguationError as ex:
out.append(Phrase().text('This can refer to a many things, such as {0}'.format(self.join_for_more(ex.options, limit=None))))
return is_exact, out
if not page and 'disambiguation' not in page_titles[0]:
try:
page = wikipedia.page(page_titles[0])
except Exception as ex:
out.append(Phrase().text(str(ex)))
if page and not out:
out.append(Phrase().text(page.content.split('==')[0]
.split('\n')[0]
.encode('utf-8', 'ignore')).pause(1))
return is_exact, out
def wikipedia_parser(ctx, message):
"""
Returns a wikipedia definition
:param ctx:
:param message:
:return:
"""
try:
querry = message.content[6:]
search = wikipedia.summary(str(querry), sentences=4)
await ctx.send_message(message.channel, "```{}```".format(search))
except wikipedia.DisambiguationError as e:
length = len(e.options)
if length == 1:
await ctx.send_message(message.channel, "Did you mean? `{}`".format(e.options[0]))
elif length == 2:
await ctx.send_message(message.channel, "Did you mean? `{}` or `{}`"
.format(e.options[0], e.options[1]))
else:
await ctx.send_message(message.channel,
"Disambiguation in you query. It can mean `{}`, `{}` and {} more."
.format(e.options[0], e.options[1], str(length)))
except wikipedia.PageError:
await ctx.send_message(message.channel, "No pages matched your querry :cry:")
except wikipedia.HTTPTimeoutError:
await ctx.send_message(message.channel, "Hey there, slow down you searches for a bit!")
except wikipedia.RedirectError:
await ctx.send_message(message.channel,
"Error: page title unexpectedly resolves to a redirect. "
"Please re-check your query.")
except wikipedia.WikipediaException:
await ctx.send_message(message.channel, "Error: The search parameter must be set.")
def wikipedia(self, context, lang: str = None, query: str = None):
''' Get a page from wikipedia and reply with an embed '''
query = self.bot.get_text(context)
if lang is not None:
if lang.startswith('(') and lang.endswith(')'):
query = query[len(lang) + 1:]
lang = lang[1:-1]
else:
lang = None
if query in [None, '', ' ']:
await self.bot.doubt(context)
return
try:
import wikipedia
if lang is not None and lang in wikipedia.languages().keys():
wikipedia.set_lang(lang)
else:
wikipedia.set_lang('en')
page = wikipedia.page(query)
summary = page.summary
if len(summary) > 1222: # totally arbitrary chosen number
summary = summary[:1220] + '...'
embed = discord.Embed(title=page.title, description=summary, url=page.url)
embed.set_footer(text=page.url)
if self.bot.config['bleeding']:
if len(page.images) > 0:
embed.set_image(url=page.images[0])
await self.bot.say(embed=embed)
await self.bot.replied(context)
except wikipedia.PageError as e:
await self.bot.reply('{}\nMake sure you search for page titles in the language that you have set.'.format(e))
await self.bot.doubt(context)
except KeyError:
pass
except wikipedia.DisambiguationError as e:
msg = '```\n{}\n```'.format(e)
await self.bot.doubt(context)
await self.bot.say(msg)