Skip to content

Commit

Permalink
migration to the new plugins structure
Browse files Browse the repository at this point in the history
+ version bump
  • Loading branch information
idooo committed Oct 19, 2014
1 parent fa412a8 commit 4ccabd0
Show file tree
Hide file tree
Showing 13 changed files with 187 additions and 29 deletions.
8 changes: 4 additions & 4 deletions pancake.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/env python

__project_name__ = 'Pancake chat bot (HipChat edition)'
__version__ = '1.0'
__version__ = '2.0.0'

import argparse
import src as library
Expand All @@ -17,9 +17,9 @@

# Config to use
conf_name = args.config
conf = library.config.Settings(conf_name)
settings = library.config.Settings(conf_name)

bot = library.Bot(conf)
bot = library.Bot(settings.get())

bot.join_rooms(conf.general['rooms'])
bot.join_rooms(settings.get('general:rooms'))
bot.start()
10 changes: 10 additions & 0 deletions plugins/blame.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@

class BlamePlugin():

help = "Blame somebody"
command = "blame"

@staticmethod
def response(random_user):
message = '{}, this is your fault!'
return message.format(random_user)
22 changes: 22 additions & 0 deletions plugins/chuck.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import requests

class ChuckNorrisPlugin():

help = "Post a random Chuck's phrase"
command = "chuck"

@staticmethod
def response():

message = "Can't connect to Chuck API =("
params = {'limitTo': '[nerdy]'}

r = requests.get('http://api.icndb.com/jokes/random', params=params)

if r.status_code == 200:
response = r.json()

if response['type'] == 'success':
message = response['value']['joke']

return message
46 changes: 46 additions & 0 deletions plugins/geckoboard.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import requests
import json

class GeckoboardPlugin():

help = "Post message to Geckoboard"
command = "board"

widget_key = None
api_key = None

def __init__(self, conf):
if not 'geckoboard' in conf:
raise Exception("There is no [geckoboard] section in the config file")

if not 'api' in conf['geckoboard'] or not 'widget' in conf['geckoboard']:
raise Exception("You must specify 'widget' and 'api' options "
"in [geckoboard] section in the config file")

self.widget_key = conf['geckoboard']['widget']
self.api_key = conf['geckoboard']['api']

def response(self, message):

message_parts = message.split(' ', 1)

params = {
"api_key": self.api_key,
"data": {
"item": [
{ "text": message_parts[1], "type":0 }
]
}
}

headers = {'Content-type': 'application/json'}
r = requests.post('https://push.geckoboard.com/v1/send/' + self.widget_key,
data=json.dumps(params), headers=headers)

if r.status_code == 200:
response = r.json()

if response['success']:
return 'Message was posted to Geckoboard'

return 'Something went wrong'
6 changes: 5 additions & 1 deletion plugins/giphy.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ class GiphyPlugin():
command = "gif"

@staticmethod
def response(message):
def response(message, author):
search_values = message.split('/gif', 1)
tags = ''
if len(search_values) == 2:
Expand All @@ -16,6 +16,10 @@ def response(message):

if r.status_code == 200:
response = r.json()

if len(response['data']) == 0:
return "{}, I have no images about that!".format(author)

return response['data']['image_url']

else:
Expand Down
11 changes: 11 additions & 0 deletions plugins/pony.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import random

class PonyPlugin():

help = "Post a random pony image"
command = "pony"

@staticmethod
def response():
max_number = 160
return "http://ponyfac.es/{}/full.jpg".format(random.randint(1, max_number))
11 changes: 11 additions & 0 deletions plugins/question.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import random

class AskMePlugin():

help = "Ask me a question"
command = "?"

@staticmethod
def response(author):
options = ['yes', 'no', 'no way!', 'yep!']
return '{0}, {1}'.format(author, random.choice(options))
10 changes: 10 additions & 0 deletions plugins/roll.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import random

class RollPlugin():

help = "Roll a random number 0 - 100"
command = "roll"

@staticmethod
def response(author):
return '{0} rolled {1}'.format(author, random.randint(0, 100))
14 changes: 14 additions & 0 deletions plugins/rps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import random

class RPSPlugin():

help = "Rock - Paper - Scissors - Lizard - Spock (type '/rps help' for help)"
command = "rps"

@staticmethod
def response(message, author):
if 'help' in message:
return 'http://a.tgcdn.net/images/products/additional/large/db2e_lizard_spock.jpg'

options = ['Rock', 'Paper', 'Scissors', 'Lizard', 'Spock']
return '{0} - {1}'.format(author, random.choice(options))
22 changes: 22 additions & 0 deletions plugins/xkcd.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import random
import requests

class XKCDPlugin():

help = "Get random xkcd comics"
command = "xkcd"

@staticmethod
def response():

max_value = 1335
value = random.randint(1, max_value)

r = requests.get('http://xkcd.com/{}/info.0.json'.format(value))

if r.status_code == 200:
response = r.json()
return [response['img'], response['alt']]

else:
return "Can't connect to xkcd API =("
14 changes: 9 additions & 5 deletions src/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ class Bot():

def __init__(self, conf):

api_token = conf.general['api_token']
name = conf.general['bot_name']
api_token = conf['general']['api_token']
name = conf['general']['bot_name']

self.hipster = HipChat(token=api_token)

Expand Down Expand Up @@ -194,15 +194,19 @@ def execute_action(self, action, room_name, message_object):

if 'room' in fields: args.update({'room': room_name})
if 'author_id' in fields: args.update({'author_id': message_object['from']['user_id']})
if 'author' in fields: args.update({'author': message_object['from']['name']})
if 'author' in fields: args.update({'author': self.__mention_user(message_object['from']['name'])})
if 'message' in fields: args.update({'message': message_object['message']})
if 'random_user' in fields: args.update({'random_user': self.__get_random_user(room_name)})
if 'mentioned_user' in fields:
args.update({'mentioned_user': self.__get_mentioned_user(room_name, message_object['message'])})

message = action(**args)
messages = action(**args)

self.post_message(room_name, message)
if not isinstance(messages, list):
messages = [messages]

for message in messages:
self.post_message(room_name, message)

def start(self):
last_dates = self.__get_latest_dates()
Expand Down
40 changes: 22 additions & 18 deletions src/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,8 @@

class Settings():

rules = {
'general': ['api_token', 'rooms', 'bot_name'],
'geckoboard': ['api', 'widget']
}

default_conf_name = 'example.conf'
__default_conf_name = 'example.conf'
__conf = {}

def __init__(self, filename=False):
"""
Expand All @@ -25,27 +21,35 @@ def __init__(self, filename=False):
self.CONF_DIR = self.APP_DIR + 'conf/'

if not filename:
filename = self.default_conf_name
filename = self.__default_conf_name
self.FILENAME = self.CONF_DIR + filename

self.CONF_NAME = filename

config = ConfigParser.ConfigParser()
config.readfp(open(self.CONF_DIR + filename))

for section in self.rules.keys():
for section_name in config.sections():
data = {}
for item in self.rules[section]:
for item in config.items(section_name):
try:
data.update({item: str(config.get(section, item)).strip()})
data.update({item[0]: str(config.get(section_name, item[0])).strip()})
except ConfigParser.NoOptionError:
data.update({item: ''})
except ConfigParser.NoSectionError:
for option in self.rules[section]:
data.update({option: False})
break
data.update({item[0]: None})

if data[item[0]].lower() == 'false':
data[item[0]] = False

self.__conf.update({
section_name: data
})

def get(self, key=None):
if not key: return self.__conf

if data[item].lower() == 'false':
data[item] = False
try:
section, option = key.split(':')
return self.__conf[section][option]
except KeyError, e:
raise Exception("Can't find config key in file: " + str(e))

setattr(self, section, data)
2 changes: 1 addition & 1 deletion src/plugin_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def load_plugin(self, filename):
args.update({'conf': self.conf})

plugin = class_name(**args)
if not hasattr(plugin, 'help') and not hasattr(plugin, 'command'):
if not hasattr(plugin, 'help') or not hasattr(plugin, 'command') or len(plugin.command) == 0:
raise Exception("Plugin class must have 'help' and 'command' attributes")

self.__check_conflicts(plugin.command)
Expand Down

0 comments on commit 4ccabd0

Please sign in to comment.