示例#1
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import sys
import requests
import json
from response import Response
from marta.api import get_buses, get_trains
from collections import defaultdict

from pb_logging import PBLogger
logger = PBLogger("MARTA")

# Since Slack wouldn't know where the first arg ends and the second begins, the first arg (station name) has to be one word
stations = {
    "AIRPORT STATION": ['airport','hartsfield','hartsfield-jackson'],
    "ARTS CENTER STATION": ['artscenter'],
    "ASHBY STATION": ['ashby'],
    "AVONDALE STATION": ['avondale'],
    "BANKHEAD STATION": ['bankhead'],
    "BROOKHAVEN STATION": ['brookhaven'],
    "BUCKHEAD STATION": ['buckhead'],
    "CHAMBLEE STATION": ['chamblee'],
    "CIVIC CENTER STATION": ['civiccenter'],
    "COLLEGE PARK STATION": ['collegepark'],
    "DECATUR STATION": ['decatur'],
    "OMNI DOME STATION": ['omnidome','dome','mercedesbenz','cnn','statefarmarena','congresscenter','gwcc'],
    "DORAVILLE STATION": ['doraville'],
    "DUNWOODY STATION": ['dunwoody'],
    "EAST LAKE STATION": ['eastlake'],
    "EAST POINT STATION": ['eastpoint'],
示例#2
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import urllib2, json
import sys
from response import Response

from pb_logging import PBLogger

logger = PBLogger("CatFact")


def run(response, args=None):
    response_obj = Response(sys.modules[__name__])
    catfact_url = "https://catfact.ninja/fact"

    try:
        raw_response = urllib2.urlopen(catfact_url).read()
        parsed_response = json.loads(raw_response)

        response_obj.messages_to_send.append(parsed_response["fact"])

    except Exception as e:
        logger.error("Error in catfacts: " + str(e))
        response_obj.status_code = -1

    return response_obj


def return_alias():
    alias_list = ["catfact"]
示例#3
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Template: Include this so this file supports unicode characters in it.

# Always import these two pieces at least
import sys
from response import Response

# Import these so that you can use the logger functions
# so that you can log things
import logging
from pb_logging import PBLogger

# If you need to print something that will be used for official logging purposes
# use this logger class using the custom handler PBHandler from the log_handler class
logger = PBLogger('Hello World')


# 'run' should have all your primary logic, and must exist
def run(
    response,
    args=None
):  # response is always given to you, good for checking on user info or something unique to a message object, args is optional but your code will not run if given arguments and this is not present, or if your function may not take args, set it to None or [] depending on your needs
    # This is your response_obj, it should be returned at the end of your script (or logic that calls for it to end early)
    # See response.py at the root of the project directory to see how it works in more depth
    response_obj = Response(sys.modules[__name__])
    # do your logic here
    message = "Hello World:"
    if args is not None:
        for x in range(
                0, len(args)
示例#4
0
    LOG (boolean): Global Variable
    LOGC (boolean): Global Variable

.. _Google Python Style Guide:
   http://google.github.io/styleguide/pyguide.html

"""

from slackclient import SlackClient
import threading, websocket, json, re, time, codecs, random, logging
import scripts
from bot import Bot

from pb_logging import PBLogger

logger = PBLogger('ReactBot')

class ReactBot(Bot):

    # Set the name for the logger
    # Add custom log handler to logger

    def __init__(self, token, bot_name=""):
        super(ReactBot, self).__init__(token, bot_name)
        self.connect_to_slack(token)

        self.annoyance = 0 # Used for the "No, this is PantherHackers" response

    def connect_to_slack(self, token):
        # Initiates connection to the server based on the token, receives websocket URL "bot_conn"
        logger.info("Starting RTM connection")
示例#5
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import upsidedown, sys
from response import Response

from pb_logging import PBLogger
logger = PBLogger("Flip")

# flips text using upsidedown module and has a donger for emohasis
def run(response, args=[]):
    response_obj = Response(sys.modules[__name__])
    toFlip = ''
    donger = '(╯°□°)╯︵'
    if len(args) >= 0:
        for n in range(0, len(args)):
            toFlip += args[n] + " "

    if toFlip == '':
        toFlip = unicode('┻━┻', "utf-8")

    try:
        donger = unicode(donger, "utf-8")
        logger.info(toFlip[:15 or len(toFlip)] + "...")
        flippedmsg = upsidedown.transform(toFlip)
        response_obj.messages_to_send.append(donger + flippedmsg)
    except Exception as e:
        logger.error(str(e))
        response_obj.status_code = -1
    return response_obj

def return_alias():
示例#6
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import sys
from response import Response

from pb_logging import PBLogger

logger = PBLogger("Fortune")


# returns a random "fortune"
def run(response):
    response_obj = Response(sys.modules[__name__])
    try:
        # get fortune
        fortune = urllib2.urlopen(
            "http://www.fortunefortoday.com/getfortuneonly.php").read(
            )  # noqa: 501
    except Exception as e:
        fortune = "Unable to reach Fortune Telling api"
        logger.error("Unable to reach Fortune Telling API: " + str(e))

    # make api call
    response_obj.messages_to_send.append(fortune)
    return response_obj


def return_alias():
    alias_list = ["fortune"]
    return alias_list
示例#7
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import upsidedown
import sys
from response import Response

from pb_logging import PBLogger
logger = PBLogger("Rage")


# flips text using upsidedown module and has a donger for emohasis
def run(response, args=[]):
    response_obj = Response(sys.modules[__name__])
    toFlip = ''
    donger = '(ノಠ益ಠ)ノ彡'
    for n in range(0, len(args)):
        toFlip += args[n] + " "

    if toFlip == '':
        toFlip = unicode('┻━┻', "utf-8")

    try:
        donger = unicode(donger, "utf-8")
        logger.info(toFlip[:15 or len(toFlip)] + "...")
        flippedmsg = upsidedown.transform(toFlip)
        response_obj.messages_to_send.append(donger + flippedmsg)
    except Exception as e:
        logger.error("Error in flip: " + str(e))
        response_obj.messages_to_send.append(
            "Sorry, I can't seem to flip right now, or you gave an invalid argument"
        )
示例#8
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import sys
from response import Response

from pb_logging import PBLogger
logger = PBLogger("Conch")


def run(response, args):
    response_obj = Response(sys.modules[__name__])
    lower_args = [arg.lower() for arg in args]
    if "or" in lower_args:
        l = ["Neither."]
    else:
        l = [
            "Yes.", "No.", "Maybe someday.", "I don't think so.",
            "Follow the seahorse.", "Try asking again."
        ]
    m = random.randrange(0, len(l))
    response_obj.messages_to_send.append(l[m])
    logger.info(l[m])
    return response_obj


def return_alias():
    alias_list = ["conch", "magicconch"]
    return alias_list

示例#9
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import sys
import urllib2, json
from response import Response

from pb_logging import PBLogger
logger = PBLogger("Summary")


# flips a coin
def run(response, args):
    response_obj = Response(sys.modules[__name__])
    res_text = ""
    if args:
        smmry_url = "http://api.smmry.com/&SM_API_KEY=CFE8330DFD&SM_URL=" + args[
            0]
        parsed_response = json.loads(urllib2.urlopen(smmry_url).read())
        if 'sm_api_content' in parsed_response:
            res_text = parsed_response['sm_api_content']
        else:
            res_text = "Whoops, something went wrong with the SMMRY API"
    else:
        res_text = "D'oh, you didn't include a link!"
    response_obj.messages_to_send.append(res_text)
    logger.info(res_text)
    return response_obj


def return_alias():
示例#10
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, time, json
import sys
from response import Response
from slackclient import SlackClient

from pb_logging import PBLogger

logger = PBLogger("Admin")

def run(message_json, args, sc, bot, rmsg):
    response_obj = Response(sys.modules[__name__])
    if args[0].lower() == "list":
        logger.info("Admin command list")
        response_obj.messages_to_send.append("The current admin commands are `list`, `add`, and `inactive-list`")
    elif args[0].lower() == "add":
        logger.info("Add admin")
        args.pop(0)
        admin_add(message_json, args, sc, bot, rmsg) 
    # This requires the user's token be authed as admin (legacy, not bot tokens bypass this need)
    elif args[0].lower() == "inactive-list":
        logger.info("Inactive list")
        args.pop(0)
        response_obj = compile_inactive_list(message_json, bot, response_obj)
    else:
        logger.info("No admin command called for")
        response_obj.messages_to_send.append("The argument `" + args[0] + "` is not a proper admin command.")
    return response_obj

def return_alias():
示例#11
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import sys
from response import Response

from pb_logging import PBLogger
logger = PBLogger("Coin")


# flips a coin
def run(response):
    response_obj = Response(sys.modules[__name__])
    l = ["Heads", "Tails"]
    m = random.randrange(0, 2)
    response_obj.messages_to_send.append(l[m])
    logger.info(l[m])
    return response_obj


def return_alias():
    alias_list = ["coin"]
    return alias_list


def is_admin_command():
    return False


def help_preview():
    return "!coin"
示例#12
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from response import Response

from pb_logging import PBLogger
logger = PBLogger("Unflip")


#"unflips" text
def run(response, args=[]):
    response_obj = Response(sys.modules[__name__])
    toUnFlip = ''
    for n in range(0, len(args)):
        toUnFlip += args[n] + " "

    if toUnFlip == "":
        toUnFlip = unicode('┬──┬', "utf-8")

    try:
        donger = "ノ( º _ ºノ)"
        donger = unicode(donger, "utf-8")
        logger.info(toUnFlip[:15 or len(toUnFlip)] + "...")
        response_obj.messages_to_send.append(toUnFlip + donger)
    except Exception as e:
        logger.error("Error in flip: " + str(e))
        response_obj.status_code = -1
    return response_obj

示例#13
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import sys
from response import Response

from pb_logging import PBLogger
logger = PBLogger("Links")

# flips a coin
def run(response, args):
    response_obj = Response(sys.modules[__name__])
    res_message = ""
    links = {
        "Website":"pantherhackers.com",
        "Slack":"pantherhackers.slack.com",
        "Instagram":"instagram.com/pantherhackers",
        "Twitter":"twitter.com/pantherhackers",
        "GitHub":"github.com/PantherHackers"
    }
    specific_link = False
    if args:
        specific_link = True
    if specific_link:
        try:
            for a in args:
                res_message = res_message + a.lower().capitalize() + ": " + links[a.lower().capitalize()] + "\n"
        except Exception as e:
            logger.error(a.lower().capitalize() + " not found in links")
            specific_link = False
            break
示例#14
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from response import Response

from pb_logging import PBLogger
from scripts import commands
logger = PBLogger("Help")


# help script that details the list of commands
def run(response, args=None):
    response_obj = Response(sys.modules[__name__])

    #Default call to !help
    if args is None:
        commands_help_text = "PantherBot works by prefacing commands with \"!\"\nCommands:\n```"
        commands_help_text += "!version\n"

        list_of_used_commands = []
        for value in commands.values():
            if value not in list_of_used_commands:
                list_of_used_commands.append(value)
                try:
                    get_help_preview = getattr(value, "help_preview")
                    commands_help_text += get_help_preview() + "\n"
                except:
                    logger.error("Module " + str(value) +
                                 " has no help_preview function")
        commands_help_text += "```\nAdmins can use `$` commands\n"
示例#15
0
import threading, time, logging, os, sys, codecs

from bot import Bot
from reactbot import ReactBot

#
from pb_logging import PBLogger

if __name__ == "__main__":
    # See here for logging documentation https://docs.python.org/2/howto/logging.html

    # Set the name for the logger
    # Add custom log handler to logger
    logger = PBLogger('PantherBot')

    # Checks if the system's encoding type is utf-8 and changes it to utf-8 if it isnt (its not on Windows by default)  # noqa: 501
    if sys.stdout.encoding != 'utf-8':
        sys.stdout = codecs.getwriter('utf-8')(sys.stdout, 'strict')
    if sys.stderr.encoding != 'utf-8':
        sys.stderr = codecs.getwriter('utf-8')(sys.stderr, 'strict')

    # Initializes our primary bot
    # This is the reactive bot known as "PantherBot," and is responsible for all message detection and immediate reactions
    logger.info("Initializing bot")
    token = os.environ.get('PB_TOKEN')

    # List of all bots running in current process.
    BOT_LIST = []
    react_bot = ReactBot(token, bot_name="PantherBot")
    BOT_LIST.append(react_bot)
    bot_thread = threading.Thread(target=react_bot.WEBSOCKET.run_forever,
示例#16
0
.. _Google Python Style Guide:
   http://google.github.io/styleguide/pyguide.html

"""

from slackclient import SlackClient

import threading, websocket, json, re, time, codecs, random, os
import scripts
from scripts import commands

from pb_logging import PBLogger
import logging 

logger = PBLogger('Bot')

class Bot(object):
    admin_env_string = os.environ['PB_ADMIN']
    ADMIN = admin_env_string.split(',')

    # Set the name for the logger
    # Add custom log handler to logger

    EMOJI_LIST = ["party-parrot", "venezuela-parrot", "star2", "fiesta-parrot", "wasfi_dust", "dab"]
    GENERAL_CHANNEL = ""
    TTPB = "talk-to-pantherbot"
    VERSION = "2.1.0"

    def __init__(self, token, bot_name=""):
        self.SLACK_CLIENT = None