Skip to content

Commit

Permalink
Merge pull request #118 from LanceMaverick/dashboard-enhancements
Browse files Browse the repository at this point in the history
Added toJSON methods to Commands and Beards.
  • Loading branch information
LanceMaverick committed Mar 11, 2017
2 parents 85e3174 + bfbcf2a commit 1702e66
Show file tree
Hide file tree
Showing 10 changed files with 69 additions and 478 deletions.
47 changes: 26 additions & 21 deletions beards/postcats/__init__.py
Original file line number Diff line number Diff line change
@@ -1,44 +1,49 @@
#show spacecats test plugin
# show spacecats test plugin
# Adapted from work by LanceMaverick
from os.path import basename
import random
import logging
from urllib.request import urlopen
import telepot
import telepot.aio
from skybeard.beards import BeardChatHandler
from skybeard.predicates import regex_predicate
from skybeard.decorators import admin


class PostCats(BeardChatHandler):
__userhelp__ = """
Say give me spacecats or show me spacecats if you want
to, well, see cats in space."""

__commands__ = [
(regex_predicate('(give|show) me spacecats'), 'send_cat',
"Sends a spacecat image"),
]

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.register_command(
regex_predicate('(give|show) me spacecats'), self.send_cat)


async def send_cat(self, msg):
cat_photos= [
'http://i.imgur.com/bJ043fy.jpg',
'http://i.imgur.com/iFDXD5L.gif',
'http://i.imgur.com/6r3cMsl.gif',
'http://i.imgur.com/JpM5jcX.jpg',
'http://i.imgur.com/r7swEJv.jpg',
'http://i.imgur.com/vLVbiKu.jpg',
'http://i.imgur.com/Yy0TCXA.jpg',
'http://i.imgur.com/2eV7kmq.gif',
'http://i.imgur.com/rnA769W.jpg',
'http://i.imgur.com/08mxOAK.jpg',
'http://i.imgur.com/Ct5GsQn.jpg',
]
cat_photos = [
'http://i.imgur.com/bJ043fy.jpg',
'http://i.imgur.com/iFDXD5L.gif',
'http://i.imgur.com/6r3cMsl.gif',
'http://i.imgur.com/JpM5jcX.jpg',
'http://i.imgur.com/r7swEJv.jpg',
'http://i.imgur.com/vLVbiKu.jpg',
'http://i.imgur.com/Yy0TCXA.jpg',
'http://i.imgur.com/2eV7kmq.gif',
'http://i.imgur.com/rnA769W.jpg',
'http://i.imgur.com/08mxOAK.jpg',
'http://i.imgur.com/Ct5GsQn.jpg',
]

try:
choice = random.choice(cat_photos)
await self.sender.sendPhoto((choice.split("/")[-1], urlopen(choice)))
await self.sender.sendChatAction('upload_photo')
await self.sender.sendPhoto(
(basename(choice), urlopen(choice)))
except Exception as e:
logging.error(e)
await self.sender.sendPhoto(
("cat_photo.jpg",
urlopen('http://cdn.meme.am/instances/500x/55452028.jpg')))
raise e
330 changes: 0 additions & 330 deletions dashboard/angular.min.js

This file was deleted.

65 changes: 0 additions & 65 deletions dashboard/app.js

This file was deleted.

6 changes: 0 additions & 6 deletions dashboard/bootstrap.min.css

This file was deleted.

24 changes: 0 additions & 24 deletions dashboard/index.html

This file was deleted.

2 changes: 0 additions & 2 deletions dashboard/index.pug

This file was deleted.

22 changes: 0 additions & 22 deletions dashboard/loaded-beards.html

This file was deleted.

2 changes: 0 additions & 2 deletions dashboard/start_web_server.sh

This file was deleted.

30 changes: 29 additions & 1 deletion skybeard/beards.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,18 @@ def __init__(self, pred, coro, hlp=None):
self.coro = coro
self.hlp = hlp

def toJSON(self):
try:
return {
"predicate": self.pred.toJSON(),
"help": self.hlp,
}
except AttributeError:
return {
"predicate": "(unserializable)",
"help": self.hlp,
}


class SlashCommand(object):
"""Holds information to determine whether a telegram command was sent."""
Expand All @@ -40,6 +52,12 @@ def __init__(self, cmd, coro, hlp=None):
self.coro = coro
self.hlp = hlp

def toJSON(self):
return {
"command": "/"+self.cmd,
"help": self.hlp
}

def create_command(cmd_or_pred, coro, hlp=None):
"""Creates a Command or SlashCommand object as appropriate.
Expand Down Expand Up @@ -168,6 +186,16 @@ async def get_username(self):

return type(self)._username

@classmethod
def toJSON(cls):
# Not a coroutine because it's useful to use this in list
# comprehensions
return {
"name": cls.__name__,
"commands": [c.toJSON() for c in cls.__commands__],
"userhelp": cls.__userhelp__
}

def __init__(self, *args, **kwargs):
self._instance_commands = []
super().__init__(*args, **kwargs)
Expand Down Expand Up @@ -289,7 +317,7 @@ async def on_chat_message(self, msg):

@app.add_route('/loadedBeards', methods=['GET'])
async def loaded_beards(request):
return web.json_response([str(x) for x in Beard.beards])
return web.json_response([b.toJSON() for b in Beard.beards])


@app.add_route('/availableCommands', methods=['GET'])
Expand Down
19 changes: 14 additions & 5 deletions skybeard/predicates.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import types
import logging
import re

Expand All @@ -7,20 +8,28 @@
def regex_predicate(pattern, lower=False):
"""Returns a predicate function which returns True if pattern is matched.
if lower == True, the text will be made lower case."""

if lower:
compiled_pattern = re.compile(pattern, re.IGNORECASE)
else:
compiled_pattern = re.compile(pattern)

def retfunc(chat_handler, msg):
try:
if lower:
text = msg['text'].lower()
else:
text = msg['text']
text = msg['text']
logger.debug("Matching regex: '{}' in '{}'".format(
pattern, text))
retmatch = re.match(pattern, text)
retmatch = compiled_pattern.match(text)
logger.debug("Match: {}".format(retmatch))
return retmatch
except KeyError:
return False

def _toJSON(self):
return str(compiled_pattern)

retfunc.toJSON = types.MethodType(_toJSON, retfunc)

return retfunc


Expand Down

0 comments on commit 1702e66

Please sign in to comment.