Skip to content

Commit

Permalink
Merge branch 'skb-dev' of https://github.com/LanceMaverick/skybeard-2
Browse files Browse the repository at this point in the history
…into skb-dev
  • Loading branch information
LanceMaverick committed Feb 28, 2017
2 parents 3484b24 + f992834 commit 82a8f89
Show file tree
Hide file tree
Showing 3 changed files with 113 additions and 34 deletions.
83 changes: 59 additions & 24 deletions skybeard/bearddbtable.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,26 +9,37 @@
logger = logging.getLogger(__name__)


class BeardDBTable(object):
class BeardDBTableBase(object):
"""Placeholder for database object for beards.
For use with async with.
For use with `with`.
If per_instance is False, then the database table is per class, rather than
per instance.
"""
def __init__(self, beard, table_name, **kwargs):
def __init__(self, beard, table_name, per_instance, **kwargs):
self.beard_name = type(beard).__name__
self.table_name = "{}_{}".format(
self.beard_name,
table_name
)
if per_instance:
self.table_name = "{}_{}_{}".format(
self.beard_name,
beard.chat_id,
table_name
)
else:
self.table_name = "{}_{}".format(
self.beard_name,
table_name
)
self.kwargs = kwargs

def __enter__(self):
self.db = dataset.connect(pyconfig.get('db_url'))
self.db.__enter__()
self.table = self.db.get_table(self.table_name, **self.kwargs)
logger.debug("BeardDBTable initalised with: self.table: {}, self.db: {}".format(
self.table, self.db))
logger.debug(
"BeardDBTable initalised with: self.table: {}, self.db: {}".format(
self.table, self.db))
return self

def __exit__(self, error_type, error_value, traceback):
Expand All @@ -39,22 +50,55 @@ def __exit__(self, error_type, error_value, traceback):

def __getattr__(self, name):
"""If the normal getattr fails, try getattr(self.table, name)."""
try:
return getattr(self.table, name)
except AttributeError:
if not hasattr(self, 'table'):
raise AttributeError(
"Open table not found. Are you using BeardDBTable with with?")

return getattr(self.table, name)


# async def get_binary_entry(path):
# return open(os.path.join(pyconfig.get('db_bin_path'), path), 'rb')
class BeardDBTable(BeardDBTableBase):
"""Placeholder for database object for beards.
For use with `with`.
"""
def __init__(self, beard, table_name, **kwargs):
super().__init__(beard, table_name, per_instance=False, **kwargs)

def __enter__(self):
super().__enter__()

return self

def __exit__(self, error_type, error_value, traceback):
super().__exit__(error_type, error_value, traceback)


class BeardInstanceDBTable(BeardDBTableBase):
"""Placeholder for database object for beards instances (i.e. per chat).
For use with `with`.
"""
def __init__(self, beard, table_name, **kwargs):
super().__init__(beard, table_name, per_instance=True, **kwargs)

def __enter__(self):
super().__enter__()

return self

def __exit__(self, error_type, error_value, traceback):
super().__exit__(error_type, error_value, traceback)


async def make_binary_entry_filename(table, key):
# Assume the random string has been found, until it's not been found.
random_string_found = True
while random_string_found:
random_string = "".join([random.choice(string.ascii_letters) for x in range(50)])
random_string = "".join(
[random.choice(string.ascii_letters) for x in range(50)])
for d in os.listdir(pyconfig.get('db_bin_path')):
if random_string in d:
break
Expand All @@ -69,12 +113,3 @@ async def make_binary_entry_filename(table, key):
primary_key,
key,
random_string))


# async def create_binary_entry(table, key, bytes_object):
# object_path = os.path.join(
# pyconfig.get('db_bin_path'),
# binary_entry_filename(table, key))
# with open(object_path, 'wb') as f:
# f.write()
# return object_path
62 changes: 53 additions & 9 deletions skybeard/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

# from skybeard.beards import BeardAsyncChatHandlerMixin
from skybeard.beards import BeardChatHandler, Beard, SlashCommand
from skybeard.mixins import PaginatorMixin
from skybeard.utils import embolden, italisize

import config
Expand All @@ -27,21 +28,44 @@ async def fetch_user_help():
return retdict


async def format_user_help(userhelps):
async def format_user_help(name, userhelp):
"""Takes a dict of user help messages and formats them."""

retstr = ""
if userhelp:
retstr += "{name}:\n{userhelp}\n\n".format(name=embolden(name), userhelp=userhelp)
else:
retstr += "{name}:\nNo documentation found.\n\n".format(name=embolden(name))

return retstr


async def format_user_helps(userhelps):
"""Takes a dict of user help messages and formats them."""

retstr = italisize("List of beard documentation:\n\n")
for name, userhelp in sorted(userhelps.items(), key=lambda x: x[0]):
if userhelp:
retstr += "{name}:\n{userhelp}\n\n".format(name=embolden(name), userhelp=userhelp)
else:
retstr += "{name}:\nNo documentation found.\n\n".format(name=embolden(name))
retstr += await format_user_help(name, userhelp)

retstr += italisize("End of beard documentation.")

return retstr


async def format_user_helps_paginated(userhelps):
"""Takes a dict of user help messages and formats them."""

retlist = []
for name, userhelp in sorted(userhelps.items(), key=lambda x: x[0]):
retstr = italisize("Beard documentation:\n\n")
retstr += await format_user_help(name, userhelp)
# retstr += italisize("End of beard documentation.")

retlist.append(retstr)

return retlist


def get_all_cmd_helps():
"""Retrieves the help messages in the tuples of each plug-in's
__commands__ list"""
Expand All @@ -65,11 +89,30 @@ async def send_help(self, msg):
retstr += ("My help message is unconfigured. To display "
"something here, add a docstring to my config.py.")

userhelp = await fetch_user_help()
userhelp = await format_user_help(userhelp)
retstr += "\n\n{}".format(userhelp)
userhelps = await fetch_user_help()
userhelps = await format_user_helps(userhelps)
retstr += "\n\n{}".format(userhelps)
await self.sender.sendMessage(retstr, parse_mode='html')

async def send_paginated_help(self, msg):
"""sends the user a combined help message for all plug-ins"""
retstr = ""
try:
retstr += config.__userhelp__
except AttributeError:
retstr += ("My help message is unconfigured. To display "
"something here, add a docstring to my config.py.")

userhelps = await fetch_user_help()
userhelps = await format_user_helps_paginated(userhelps)

async def identity(x):
return x

await self.send_paginated_message(userhelps, identity)
# retstr += "\n\n{}".format(userhelps)
# await self.sender.sendMessage(retstr, parse_mode='html')

async def cmd_helps(self, msg):
"""sends the user a formatted list of commands for easy registering with
botfather"""
Expand All @@ -81,11 +124,12 @@ async def cmd_helps(self, msg):

def create_help(config):

class BeardedHelp(Help, BeardChatHandler):
class BeardedHelp(Help, PaginatorMixin, BeardChatHandler):
"""Beard for interfacing help functionality with telegram"""
_timeout = 2
__commands__ = [
('help', 'send_help', "Shows verbose help message."),
('helppaged', 'send_paginated_help', "Shows verbose help message, paginated."),
('cmdhelps', 'cmd_helps', "Lists all commands available."),
]

Expand Down
2 changes: 1 addition & 1 deletion skybeard/predicates.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def command_predicate(cmd):
"""Returns a predicate coroutine which returns True if command is sent."""
async def retcoro(beard_chat_handler, msg):
bot_username = await beard_chat_handler.get_username()
pattern = r"^/{}(?:@{}|[^@]|$)".format(
pattern = r"^/{}(?:@{}| |$)".format(
cmd,
bot_username,
)
Expand Down

0 comments on commit 82a8f89

Please sign in to comment.