Skip to content

Commit

Permalink
Merge pull request #130 from LanceMaverick/getargsdecorators
Browse files Browse the repository at this point in the history
⚠️ All decorators now use factory pattern
  • Loading branch information
LanceMaverick committed May 14, 2017
2 parents 578ea1b + 82ec18e commit 236ba30
Show file tree
Hide file tree
Showing 28 changed files with 315 additions and 128 deletions.
2 changes: 1 addition & 1 deletion beards/debugbeard/python/debugbeard/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class DebugBeard(BeardChatHandler):
('getme', 'who_am_i', "Returns JSON for bot.getMe().")
]

@onerror
@onerror()
async def who_am_i(self, msg):
await self.sender.sendMessage(str(await self.bot.getMe()))

Expand Down
4 changes: 2 additions & 2 deletions beards/mathbeard/python/mathbeard/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class Calculator(BeardChatHandler):
__commands__ = [
('calc','calculate','Performs a calculation')]

@onerror
@onerror()
async def calculate(self, msg):

#extract the equation input by the user
Expand All @@ -40,4 +40,4 @@ async def calculate(self, msg):
result = eq.evalf(10)


await self.sender.sendMessage(result)
await self.sender.sendMessage(result)
8 changes: 4 additions & 4 deletions beards/natrailenq/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,26 +27,26 @@ class NationalRailDepartures(BeardChatHandler):
("disruptions", "getDisruptions", "Check Information on disruptions to today's services."),
]

@onerror
@onerror()
async def searchStats(self, msg):
natRail = NatRail.RailScraper(config.rail_url, config.stat_codes)
out = format_msg(msg)
out, other = natRail.searchStations(out)
await self.sender.sendMessage(out)

@onerror
@onerror()
async def getStatus(self, msg):
natRail = NatRail.RailScraper(config.rail_url, config.stat_codes)
output = natRail.getStatus()
await self.sender.sendMessage(output, parse_mode="Markdown")

@onerror
@onerror()
async def getDisruptions(self, msg):
natRail = NatRail.RailScraper(config.rail_url, config.stat_codes)
output = natRail.getNews(format_msg(msg))
await self.sender.sendMessage(output, parse_mode="Markdown")

@onerror
@onerror()
async def checkTimes(self, msg):
natRail = NatRail.RailScraper(config.rail_url, config.stat_codes)
out = format_msg(msg)
Expand Down
8 changes: 4 additions & 4 deletions beards/relay_beard/python/relay_beard/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ class RelayBeard(BeardChatHandler):

# __init__ is implicit

@admin
@onerror
@admin()
@onerror()
async def get_key(self, msg):
with type(self).key_table as table:
e = table.find_one(user_id=msg['from']['id'])
Expand All @@ -45,8 +45,8 @@ async def get_key(self, msg):

await self.sender.sendMessage("Key is: {}".format(e['key']))

@admin
@onerror
@admin()
@onerror()
async def revoke_key(self, msg):
with type(self).key_table as table:
e = table.find_one(user_id=msg['from']['id'])
Expand Down
2 changes: 1 addition & 1 deletion beards/repo_helper/python/repo_helper/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class RepoHelper(BeardChatHandler):

# __init__ is implicit

@onerror
@onerror()
async def make_repo_yaml(self, msg):
args = get_args(msg)
try:
Expand Down
2 changes: 1 addition & 1 deletion beards/sentiment/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ async def log_message_score(self, msg):
msg['from']['first_name']))

await sent.save(msg, score)
@onerror
@onerror()
async def report(self, msg):
await self.sender.sendMessage('Generating report...')
await self.sender.sendChatAction('upload_photo')
Expand Down
2 changes: 1 addition & 1 deletion beards/teleplot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class TelePlotSB(BeardChatHandler):
("teleplot", "makePlot", "make a plot." ),
]

@onerror
@onerror()
async def makePlot(self, msg):
logger = logging.getLogger("TelePlot")
logger.setLevel(logging.DEBUG)
Expand Down
8 changes: 4 additions & 4 deletions beards/todo/python/todo/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def __init__(self, *args, **kwargs):
logger.debug("Creating BeardDBTable.")
self.todo_table = BeardDBTable(self, 'todos')

@onerror
@onerror()
async def add_todo(self, msg):
u_id = msg['from']['id']
args = get_args(msg)
Expand Down Expand Up @@ -65,7 +65,7 @@ async def _get_user_items(self, u_id):
items = [match for match in matches]
return items

@onerror
@onerror()
async def get_todo(self, msg):
u_id = msg['from']['id']
items = await self._get_user_items(u_id)
Expand All @@ -77,7 +77,7 @@ async def get_todo(self, msg):
text = 'TODO list. Click an entry to delete it',
reply_markup = keyboard)

@onerror
@onerror()
async def clear_todo(self, msg):
await self.sender.sendMessage('Are you sure you want to clear your to-do list? (yes/no)')
reply = await self.listener.wait()
Expand All @@ -91,7 +91,7 @@ async def clear_todo(self, msg):
else:
await self.sender.sendMessage('List was not cleared.')

@onerror
@onerror()
async def on_callback_query(self, msg):
query_id, from_id, query_data = glance(msg, flavor='callback_query')
match = None
Expand Down
2 changes: 1 addition & 1 deletion beards/willbeard/python/willbeard/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class WillBeard(BeardChatHandler):
'queries the W.I.L.L assistant')
]

@onerror
@onerror()
async def query_will(self, msg):
query_text = msg['text'].split(', ', 1)[1]
if any(w in query_text.lower() for w in filter_words):
Expand Down
1 change: 1 addition & 0 deletions examples/askfor/README.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
A beard named askfor for skybeard-2.
36 changes: 36 additions & 0 deletions examples/askfor/python/askfor/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
from skybeard.beards import BeardChatHandler
from skybeard.decorators import onerror, askfor, getargsorask, getargs


class Askfor(BeardChatHandler):

__userhelp__ = """Default help message."""

__commands__ = [
# command, callback coro, help text
("getargs", 'get_args', 'Gets two arguments and sends then back.'),
("askforstuff", 'ask_for_stuff', 'Asks for two arguments and echos them back.'),
("optionalargsdemo", 'optional_args_demo', 'Asks for arguments if not provided (2 args.)'),
]

# __init__ is implicit

@onerror()
@getargs()
async def get_args(self, msg, var_x, var_y):
await self.sender.sendMessage("1) {}\n2) {}".format(
var_x, var_y))

@onerror()
@askfor([('var_x', "What's your first variable?"),
('var_y', "What's your second variable?")])
async def ask_for_stuff(self, msg, var_x, var_y):
await self.sender.sendMessage("1) {}\n2) {}".format(
var_x, var_y))

@onerror()
@getargsorask([('var_x', "What's your first variable?"),
('var_y', "What's your second variable?")])
async def optional_args_demo(self, msg, var_x, var_y):
await self.sender.sendMessage("1) {}\n2) {}".format(
var_x, var_y))
5 changes: 5 additions & 0 deletions examples/askfor/setup_beard.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from skybeard.utils import setup_beard

setup_beard(
"askfor",
)
4 changes: 2 additions & 2 deletions examples/database/python/database/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@ def __init__(self, *args, **kwargs):
logger.debug("Creating BeardDBTable.")
self.test_table = BeardDBTable(self, 'test')

@onerror
@onerror()
async def write_to_db(self, msg):
random_number = random.random()
await self.sender.sendMessage(
"Attempting to write value to db: {}".format(random_number))
with self.test_table as table:
table.insert(dict(random_number=random_number))

@onerror
@onerror()
async def last_written_to_db(self, msg):
with self.test_table as table:
for x in table.all():
Expand Down
1 change: 1 addition & 0 deletions examples/debugonlyexample/README.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
A beard named debugonlyexample for skybeard-2.
20 changes: 20 additions & 0 deletions examples/debugonlyexample/python/debugonlyexample/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from skybeard.beards import BeardChatHandler
from skybeard.decorators import onerror, debugonly


class DebugOnlyExample(BeardChatHandler):

__userhelp__ = """Default help message."""

__commands__ = [
("debugonlytest", 'debug_only_test',
'Tests if skybeard is in debug mode.')
]

# __init__ is implicit

@onerror()
@debugonly("Skybeard is not in debug mode.")
async def debug_only_test(self, msg):
# This message will only be sent if skybeard is run in debug mode
await self.sender.sendMessage("You are in debug mode!")
5 changes: 5 additions & 0 deletions examples/debugonlyexample/setup_beard.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from skybeard.utils import setup_beard

setup_beard(
"debugonlyexample",
)
2 changes: 1 addition & 1 deletion examples/onerror/python/onerror/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class OnError(BeardChatHandler):
("veryfancyonerror", 'very_fancy_on_error', 'Displays very non-default <code>@onerror</code> behaviour')
]

@onerror
@onerror()
async def on_error(self, msg):
raise Exception

Expand Down
4 changes: 2 additions & 2 deletions skybeard/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,14 @@ class APIBeard(BeardChatHandler):
async def who_am_i(self, msg):
await self.sender.sendMessage("Current chat_id: "+str(self.chat_id))

@admin
@admin()
async def all_keys(self, msg):
return await self.sender.sendMessage("All keys are:\n{}".format(
"\n".join((
"{}:{}".format(
x["chat_id"], x["key"]) for x in database.get_all_keys()))))

@admin
@admin()
async def get_key(self, msg):
entry = database.get_key(self.chat_id)
return await self.sender.sendMessage("Your key: {}".format(entry["key"]))
2 changes: 1 addition & 1 deletion skybeard/beards.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ def on_close(self, e):
super().on_close(e)

async def __onerror__(self, e):
"""Runs when functions decorated with @onerror except.
"""Runs when functions decorated with @onerror() except.
Useful for emitting debug crash logs. Can be overridden to use custom
error tracking (e.g. telegramming the author of the beard when a crash
Expand Down
102 changes: 0 additions & 102 deletions skybeard/decorators.py

This file was deleted.

6 changes: 6 additions & 0 deletions skybeard/decorators/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from .admin import admin
from .onerror import onerror
from .getargs import getargs
from .askfor import askfor
from .getargsorask import getargsorask
from .debugonly import debugonly

0 comments on commit 236ba30

Please sign in to comment.