Skip to content

Commit

Permalink
wikipedia: use bot.say()'s trailing parameter for ledes ("snippets")
Browse files Browse the repository at this point in the history
We sacrifice the ability to know for sure if another Sopel bot's wiki
output was what triggered this call, but gain the ability to include
more of the article text (and test out a hack of the `trailing` param
that will be useful for other plugins with truncatable content that's
not at the very end of the message).

Replaced the `msg_url == trigger` check with a heuristic: Assume that
the triggering user was a Sopel bot if the trigger started with
`[wikipedia] ` and ended with ` | <our wiki page URL>`. Obviously it
won't be a super effective check if two different versions of Sopel with
different Wikipedia output meet, but the old check would also break in
that case. The change seems worthwhile.
  • Loading branch information
dgw committed Dec 1, 2020
1 parent e3eb41e commit 54aa021
Showing 1 changed file with 14 additions and 7 deletions.
21 changes: 14 additions & 7 deletions sopel/modules/wikipedia.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,26 +152,33 @@ def mw_search(server, query, num):
def say_snippet(bot, trigger, server, query, show_url=True):
page_name = query.replace('_', ' ')
query = quote(query.replace(' ', '_'))
url = 'https://{}/wiki/{}'.format(server, query)

# If the trigger looks like another instance of this plugin, assume it is
if trigger.startswith(PLUGIN_OUTPUT_PREFIX) and trigger.endswith(' | ' + url):
return

try:
snippet = mw_snippet(server, query)
except KeyError:
if show_url:
bot.reply("Error fetching snippet for \"{}\".".format(page_name))
return
msg = '{} | "{}"'.format(page_name, snippet)
msg_url = msg + ' | https://{}/wiki/{}'.format(server, query)
if msg_url == trigger: # prevents triggering on another instance of Sopel
return

msg = '{} | "{}'.format(page_name, snippet)

trailing = '"'
if show_url:
msg = msg_url
bot.say(msg)
trailing += ' | ' + url

bot.say(msg, trailing=' […]' + trailing)


def mw_snippet(server, query):
"""Retrieves a snippet of the given page from the given MediaWiki server."""
snippet_url = ('https://' + server + '/w/api.php?format=json'
'&action=query&prop=extracts&exintro&explaintext'
'&exchars=300&redirects&titles=')
'&exchars=500&redirects&titles=')
snippet_url += query
snippet = get(snippet_url).json()
snippet = snippet['query']['pages']
Expand Down

0 comments on commit 54aa021

Please sign in to comment.