Skip to content

Handle empty messages in bot framework by default #58

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion zulip_bots/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,9 +107,11 @@ Each bot library simply needs to do the following:

- Define a class that supports the methods `usage`
and `handle_message`.
- Optionally add a class member `ACCEPT_EMPTY_MESSAGES`, to
specify that empty messages will be passed to the bot.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be awesome if you could also add this to bots_guide.md. The guide is quite outdated, but it will be the foundation for a major refactoring.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If these commits go through, rather than the other, then I'll look into that; I wasn't sure if one was outdated, or both should be updated.

- Set `handler_class` to be the name of that class.

(We make this a two-step process to reduce code repetition
(We make this a three-step process to reduce code repetition
and to add abstraction.)

## Portability
Expand Down
5 changes: 5 additions & 0 deletions zulip_bots/zulip_bots/bots/wikipedia/wikipedia.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ class WikipediaHandler(object):
kind of external issue tracker as well.
'''

META = {'name': 'Wikipedia',
'description': 'Searches Wikipedia for a term and returns the top article.',
'no_defaults': True, # Let bot handle all messages
}

def usage(self):
return '''
This plugin will allow users to directly search
Expand Down
12 changes: 12 additions & 0 deletions zulip_bots/zulip_bots/bots/xkcd/xkcd.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
XKCD_TEMPLATE_URL = 'https://xkcd.com/%s/info.0.json'
LATEST_XKCD_URL = 'https://xkcd.com/info.0.json'

from collections import OrderedDict

class XkcdHandler(object):
'''
This plugin provides several commands that can be used for fetch a comic
Expand All @@ -14,6 +16,16 @@ class XkcdHandler(object):
commands.
'''

META = {'name': 'XKCD',
'description': 'Fetches comic strips from https://xkcd.com.',
'no_defaults': False,
'commands': OrderedDict([
('latest', "Show the latest comic strip"),
('random', "Show a random comic strip"),
('<comic id>', "Show a comic strip with a specific 'comic id'"),
])
}

def usage(self):
return '''
This plugin allows users to fetch a comic strip provided by
Expand Down
66 changes: 66 additions & 0 deletions zulip_bots/zulip_bots/lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@

from zulip import Client

from collections import OrderedDict

def exit_gracefully(signum, frame):
# type: (int, Optional[Any]) -> None
sys.exit(0)
Expand Down Expand Up @@ -156,7 +158,59 @@ def run_message_handler_for_bot(lib_module, quiet, config_file, bot_name):

state_handler = StateHandler()

# Bot details and default commands from defaults, then override if provided
bot_details = { 'name': bot_name.capitalize(),
'description': "",
'commands': {},
'no_defaults': False,
}
def def_about():
desc = bot_details['description']
return "**{}**{}".format(bot_details['name'],
"" if desc == "" else ": {}".format(desc))
def def_help():
return ("\n".join("**{}** - {}".format(k, v[1])
for k, v in default_commands.items() if k != '') +
"\n" +
"\n".join("**{}** - {}".format(k, v)
for k, v in bot_details['commands'].items() if k != ''))
def def_commands():
return "**Commands**: {} {}".format(
" ".join(k for k in default_commands if k != ''),
" ".join(k for k in bot_details['commands'] if k != ''))
default_commands = OrderedDict([
('', lambda: ("Oops. Your message was empty.", )),
('about', (def_about, "The type and use of this bot")),
('usage', ((lambda: message_handler.usage(), "Bot-provided usage text"))),
('help', (lambda: "{}\n{}\n{}".format(def_about(), message_handler.usage(), def_help()),
"This help text")),
('commands', (def_commands, "A short list of supported commands"))
])
# Update bot_details from those in class, if present
try:
bot_details.update(lib_module.handler_class.META)
except AttributeError:
pass
# Update default_commands from any changes in bot_details
if bot_details['no_defaults']: # Bot class will handle all commands
default_commands = {}
else:
if len(bot_details['commands']) == 0: # No commands specified, so don't use this feature
del default_commands['commands']
del default_commands['help']
else:
for command in bot_details['commands']: # Bot commands override defaults
if command in default_commands:
del default_commands[command]
# Sync default_commands changes with bot_details
if len(default_commands) == 0:
bot_details['no_defaults'] = True
>>>>>>> 49217e1... Bots: Alternative extended default commands approach.

if not quiet:
print("Running {} Bot:".format(bot_details['name']))
if bot_details['description'] != "":
print("\n{}".format(bot_details['description']))
print(message_handler.usage())

def extract_query_without_mention(message, client):
Expand Down Expand Up @@ -198,6 +252,18 @@ def handle_message(message):
return

if is_private_message or is_mentioned:
# Handle any default_commands first
if len(default_commands) > 0:
if '' in default_commands and len(message['content']) == 0:
restricted_client.send_reply(message, default_commands[''][0]())
return
for command in default_commands:
if command == '':
continue
if message['content'].startswith(command):
restricted_client.send_reply(message, default_commands[command][0]())
return
# ...then pass anything else to bot to deal with
message_handler.handle_message(
message=message,
bot_handler=restricted_client,
Expand Down