Skip to content

Commit

Permalink
Merge pull request #1995 from sopel-irc/modules-use-bot.say-trailing
Browse files Browse the repository at this point in the history
modules: use `bot.say()`'s `trailing` parameter
  • Loading branch information
dgw authored Jan 2, 2021
2 parents dc2b493 + 54aa021 commit c4a812e
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 51 deletions.
30 changes: 15 additions & 15 deletions sopel/modules/instagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,11 @@ def instaparse(bot, trigger, match):
# Get the embedded JSON
json = get_insta_json(instagram_url)
try:
bot.say(parse_insta_json(json))
bot.say(parse_insta_json(json), trailing='…')
except ParseError:
try:
json = get_oembed_json(instagram_url)
bot.say(parse_oembed_json(json))
bot.say(parse_oembed_json(json), trailing='…')
except ParseError:
LOGGER.exception(
"Unable to find Instagram's payload for URL %s", instagram_url)
Expand Down Expand Up @@ -121,19 +121,6 @@ def parse_insta_json(json):
else:
parts.append('%s unknown user' % title)

# Media caption
try:
icap = needed['edge_media_to_caption']['edges'][0]['node']['text']
# Strip newlines
icap = icap.replace('\n', ' ')
# Truncate caption
icap = (icap[:256] + '…') if len(icap) > 256 else icap
except (KeyError, IndexError):
icap = None

if icap:
parts.append(icap)

# Media width and height
iwidth = dimensions.get('width') or None
iheight = dimensions.get('height') or None
Expand Down Expand Up @@ -162,6 +149,19 @@ def parse_insta_json(json):
pubdate = datetime.utcfromtimestamp(idate).strftime(dateformat)
parts.append('Uploaded: %s' % pubdate)

# Media caption
# Goes last so Sopel can take care of truncating it automatically
# instead of hard-coding an arbitrary maximum length.
try:
icap = needed['edge_media_to_caption']['edges'][0]['node']['text']
# Strip newlines
icap = icap.replace('\n', ' ')
except (KeyError, IndexError):
icap = None
finally:
if icap:
parts.append(icap)

# Build the message
return ' | '.join(parts)

Expand Down
11 changes: 4 additions & 7 deletions sopel/modules/reddit.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
import datetime as dt
import re
import sys
import textwrap

import praw
import prawcore
Expand Down Expand Up @@ -238,15 +237,12 @@ def comment_info(bot, trigger, match):

# stolen from the function I (dgw) wrote for our github plugin
lines = [line for line in c.body.splitlines() if line and line[0] != '>']
short = textwrap.wrap(lines[0], 250)[0]
if len(lines) > 1 or short != lines[0]:
short += ' […]'

message = message.format(
author=author, points=c.score, points_text=points_text,
posted=posted, comment=short)
posted=posted, comment=' '.join(lines))

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


def subreddit_info(bot, trigger, match, commanded=False):
Expand Down Expand Up @@ -309,7 +305,8 @@ def subreddit_info(bot, trigger, match, commanded=False):
message = message.format(
link=link, nsfw=nsfw, subscribers='{:,}'.format(s.subscribers),
created=created, public_description=s.public_description)
bot.say(message)

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


def redditor_info(bot, trigger, match, commanded=False):
Expand Down
5 changes: 1 addition & 4 deletions sopel/modules/tld.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,11 +338,8 @@ def gettld(bot, trigger):
items.append('{}: {}'.format(field, value))

message = ' | '.join(items)
usable, excess = tools.get_sendable_message(message)
if excess:
message = usable + ' […]'

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


@plugin.command('tldcache')
Expand Down
33 changes: 16 additions & 17 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 All @@ -193,7 +200,7 @@ def say_section(bot, trigger, server, query, section):
return

msg = '{} - {} | "{}"'.format(page_name, section.replace('_', ' '), snippet)
bot.say(msg)
bot.say(msg, trailing=' […]"')


def mw_section(server, query, section):
Expand Down Expand Up @@ -225,15 +232,7 @@ def mw_section(server, query, section):
parser = WikiParser(section.replace('_', ' '))
parser.feed(data['parse']['text']['*'])
text = parser.get_result()
text = ' '.join(text.split()) # collapse multiple whitespace chars

trimmed = False

while len(text) > (420 - len(query) - len(section) - 18):
text = text.rsplit(None, 1)[0]
trimmed = True
if trimmed:
text += '...'
text = ' '.join(text.split()) # collapse multiple whitespace chars

return text

Expand Down
12 changes: 4 additions & 8 deletions sopel/modules/wiktionary.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,14 +119,12 @@ def wiktionary(bot, trigger):
return

result = format(word, definitions)
if len(result) < 150:
if len(result) < 300:
result = format(word, definitions, 3)
if len(result) < 150:
if len(result) < 300:
result = format(word, definitions, 5)

if len(result) > 300:
result = result[:295] + '[…]'
bot.say(result)
bot.say(result, trailing=' […]')


@plugin.command('ety')
Expand All @@ -146,6 +144,4 @@ def wiktionary_ety(bot, trigger):

result = "{}: {}".format(word, etymology)

if len(result) > 300:
result = result[:295] + '[...]'
bot.say(result)
bot.say(result, trailing=' […]')

0 comments on commit c4a812e

Please sign in to comment.