Beispiel #1
0
class CustomSearchApi():
    API_KEY = ConfigLoader.load("google_api_key")
    SEARCH_ENGINE_ID = ConfigLoader.load("search_engine_id")
    URL = "https://www.googleapis.com/customsearch/v1"

    class NetworkError(RuntimeError):
        def __init__(self, url, status_code, message=""):
            self.url = url
            self.status_code = status_code
            self.message = message if message else \
              "%d while requesting %s" % (status_code, url)

    def list(self, q, **kwargs):
        Log.d("Searching: %s" % q)
        if not q:
            return {}
        args = dict(kwargs)
        args.update({
            "key": self.API_KEY,
            "cx": self.SEARCH_ENGINE_ID,
            "safe": "medium",
            "q": q,
        })
        with http_request("GET", self.URL, params=args) as response:
            if response.status_code != 200:
                Log.e("Failed while list: %d" % response.status_code)
                if response.text:
                    raise self.NetworkError(url=self.URL,
                                            status_code=response.status_code,
                                            message=response.text)
                else:
                    raise self.NetworkError(url=self.URL,
                                            status_code=response.status_code)
            else:
                return response.json()
Beispiel #2
0
def test_pass_bad_project_arg_to_config_loader():
    '''config_loader should raise an exception when a bad cli arg is passed'''
    arg_type = "projects"
    arg_val = "BADARGUMENT"
    config = ConfigLoader()
    with pytest.raises(KeyError) as ke:
        config.validate(arg_type, arg_val)
        assert KeyError in str(ke.value)
Beispiel #3
0
	def run(self):
		url = ConfigLoader.load("paw_app")["url"]
		secret = ConfigLoader.load("paw_app")["webhook_secret"]

		app = Flask(__name__)
		def _webhook_view():
			return self._on_webhook()
		app.add_url_rule("/%s" % secret, view_func = _webhook_view,
				methods = ["POST"])

		global flask_app
		flask_app = app

		self._bot.setWebhook("%s/%s" % (url, secret), max_connections = 1)
Beispiel #4
0
class StandaloneApp():
    TELEGRAM_TOKEN = ConfigLoader.load("telegram_bot_token")

    def __init__(self):
        Log.i("Initializing standalone app")
        self._bot = telepot.Bot(self.TELEGRAM_TOKEN)
        self._answerer = telepot.helper.Answerer(self._bot)

    def run(self):
        import time
        self._start()
        Log.i("Running...")
        while True:
            time.sleep(10)

    def _start(self):
        Log.i("Starting app")

        def _listener(msg):
            self._on_message(msg)

        def _inline_listener(msg):
            self._on_inline_message(msg)

        self._bot.setWebhook("")
        self._bot.message_loop({
            "chat": _listener,
            "inline_query": _inline_listener,
        })

    def _on_message(self, msg):
        MessageHandler(self._bot, msg).handle()

    def _on_inline_message(self, msg):
        InlineMessageHandler(self._bot, self._answerer, msg).handle()
Beispiel #5
0
def _ensure_allowed_users(user):
	allows = ConfigLoader.load("allow_only_users")
	if not allows:
		# Empty list == allow all
		return
	# Allow if either id or username is whitelisted
	if user["id"] in allows:
		return
	elif "username" in user and user["username"] in allows:
		return
	else:
		raise _WhitelistException()
Beispiel #6
0
class PawApp():
	TELEGRAM_TOKEN = ConfigLoader.load("telegram_bot_token")

	def __init__(self):
		Log.i("Initializing PAW app")
		self._init_paw_telepot()
		self._bot = telepot.Bot(self.TELEGRAM_TOKEN)

	def run(self):
		url = ConfigLoader.load("paw_app")["url"]
		secret = ConfigLoader.load("paw_app")["webhook_secret"]

		app = Flask(__name__)
		def _webhook_view():
			return self._on_webhook()
		app.add_url_rule("/%s" % secret, view_func = _webhook_view,
				methods = ["POST"])

		global flask_app
		flask_app = app

		self._bot.setWebhook("%s/%s" % (url, secret), max_connections = 1)

	def _init_paw_telepot(self):
		# You can leave this bit out if you're using a paid PythonAnywhere
		# account
		proxy_url = "http://proxy.server:3128"
		telepot.api._pools = {
			"default": urllib3.ProxyManager(proxy_url = proxy_url, num_pools = 3,
					maxsize = 10, retries = False, timeout = 30),
		}
		telepot.api._onetime_pool_spec = (urllib3.ProxyManager,
				dict(proxy_url = proxy_url, num_pools = 1, maxsize = 1,
						retries = False, timeout = 30))
		# end of the stuff that's only needed for free accounts

	def _on_webhook(self):
		update = request.get_json()
		if "message" in update:
			# message request
			MessageHandler(self._bot, update["message"]).handle()
		elif "inline_query" in update:
			# inline request
			InlineMessageNoThreadHandler(self._bot, update["inline_query"]) \
					.handle()
		return "OK"
Beispiel #7
0
class StandaloneApp:
    TELEGRAM_TOKEN = ConfigLoader.load("telegram_bot_token")

    def __init__(self):
        Log.i("Initializing standalone app")
        self._bot = telepot.Bot(self.TELEGRAM_TOKEN)

    def run(self):
        import time
        self._start()
        Log.i("Running...")
        while True:
            time.sleep(10)

    def _start(self):
        Log.i("Starting app")

        def _listener(msg):
            self._on_message(msg)

        def _callback_query_listener(msg):
            self._on_callback_query(msg)

        self._bot.setWebhook("")
        self._bot.message_loop({
            "chat": _listener,
            "callback_query": _callback_query_listener,
        })

    def _on_message(self, msg):
        MessageHandler(self._bot, msg, self._make_session_class()).handle()

    def _on_callback_query(self, msg):
        CallbackQueryHandler(self._bot, msg,
                             self._make_session_class()).handle()

    def _make_session_class(self):
        sqlite_engine = create_engine("sqlite:///poll.db", echo=True)
        return sessionmaker(bind=sqlite_engine)
Beispiel #8
0
def test_pass_good_project_arg_to_config_loader():
    '''config_loader should return 'true' when a good cli arg and active project is passed'''
    arg_type = "platforms"
    arg_val = "usa"
    config = ConfigLoader()
    assert config.validate(arg_type, arg_val) == 'usa'
Beispiel #9
0
def test_pass_good_project_arg_to_config_loader():
    '''config_loader should return 'true' when a good cli arg and active project is passed'''
    arg_type = "environments"
    arg_val = "dev"
    config = ConfigLoader()
    assert config.validate(arg_type, arg_val) == 'dev'
Beispiel #10
0
def test_instantiate_config_loader():
    '''init should read in the config.ini file successfully'''
    config = ConfigLoader()
    assert isinstance(config, ConfigLoader) == True
Beispiel #11
0
def test_pass_good_project_arg_to_config_loader():
    '''config_loader should return 'false' when a good cli arg inactive project is passed'''
    arg_type = "projects"
    arg_val = "media-core-ui"
    config = ConfigLoader()
    assert config.validate(arg_type, arg_val) == 'false'
Beispiel #12
0
class PawApp():
    TELEGRAM_TOKEN = ConfigLoader.load("telegram_bot_token")

    def __init__(self):
        Log.i("Initializing PAW app")
        self._init_paw_telepot()
        self._bot = telepot.Bot(self.TELEGRAM_TOKEN)

    def run(self):
        url = ConfigLoader.load("paw_app")["url"]
        secret = ConfigLoader.load("paw_app")["webhook_secret"]

        app = Flask(__name__)

        def _webhook_view():
            return self._on_webhook()

        app.add_url_rule("/%s" % secret,
                         view_func=_webhook_view,
                         methods=["POST"])

        global flask_app
        flask_app = app

        self._bot.setWebhook("%s/%s" % (url, secret), max_connections=1)

    def _init_paw_telepot(self):
        # You can leave this bit out if you're using a paid PythonAnywhere
        # account
        proxy_url = "http://proxy.server:3128"
        telepot.api._pools = {
            "default":
            urllib3.ProxyManager(proxy_url=proxy_url,
                                 num_pools=3,
                                 maxsize=10,
                                 retries=False,
                                 timeout=30),
        }
        telepot.api._onetime_pool_spec = (urllib3.ProxyManager,
                                          dict(proxy_url=proxy_url,
                                               num_pools=1,
                                               maxsize=1,
                                               retries=False,
                                               timeout=30))
        # end of the stuff that's only needed for free accounts

    def _on_webhook(self):
        update = request.get_json()
        self._handle_update(update)
        return "OK"

    def _handle_update(self, update):
        if "update_id" in update:
            if not self._should_process_update(update["update_id"]):
                return

        if "message" in update:
            # message request
            MessageHandler(self._bot, update["message"],
                           self._make_session_class()).handle()
        elif "callback_query" in update:
            # inline request
            CallbackQueryHandler(self._bot, update["callback_query"],
                                 self._make_session_class()).handle()

    def _should_process_update(self, update_id):
        import datetime
        now = datetime.datetime.utcnow()
        dt = datetime.timedelta(weeks=1)
        from_time = now - dt
        with model.open_session(self._make_session_class()) as s:
            count = s.query(model.HandledUpdate) \
              .filter(model.HandledUpdate.update_id == update_id) \
              .filter(model.HandledUpdate.created_at >= from_time) \
              .count()
            if count == 0:
                # Add this update
                m = model.HandledUpdate(update_id=update_id)
                s.add(m)
            # Cleanup old ones
            s.query(model.HandledUpdate) \
              .filter(model.HandledUpdate.created_at < from_time) \
              .delete(synchronize_session = False)
            return (count == 0)

    def _make_session_class(self):
        sqlite_engine = create_engine("sqlite:///poll.db", echo=True)
        return sessionmaker(bind=sqlite_engine)