def channel_routes(): route_map = {} bot_name = settings.env('BOT', default='Echo') bot_module = importlib.import_module(f'bot.{bot_name.lower()}') bot_class = getattr(bot_module, bot_name) bot = bot_class() channel_names = settings.env('CHANNELS', default='Basic') for channel_name in channel_names.split(','): channel_module = importlib.import_module(f'channel.{channel_name.lower()}') channel_class = getattr(channel_module, channel_name) channel = channel_class(bot) for method, route, handler in channel.routes(): scoped_route = f'/{channel_name.lower()}/{route}' if scoped_route in route_map: raise RuntimeError(f'Conflicting channel route: {scoped_route}') if method == 'GET': route_map[scoped_route] = web.get(scoped_route, handler) elif method == 'POST': route_map[scoped_route] = web.post(scoped_route, handler) else: raise RuntimeError(f'Unsupported method defined for {scoped_route}: {method}') logging.info(f'Route registered: {method} {scoped_route}') return route_map.values()
def fillEnvironmentVariables(item): variables = {} text = json.dumps(item) for variable in findall('#ENV_([^#"]+)#', text): value = settings.env(variable, None) if not value: return None else: variables[variable] = value for name in variables: text = text.replace('#ENV_%s#' % name, variables[name]) return json.loads(text)
def search(self): print 'Services#search', request.form origin = request.form['from'] destination = request.form['dest'] data = {'origin': origin, 'destination': destination} url = "https://maps.googleapis.com/maps/api/directions/json?" + urlencode( data) + "&sensor=false&key=" + settings.env()['KEY'] print 'url', url # notice this is 'requests' not 'request' # we are using the request modules, 'get' function to send a request from our controller # then we use ".content" to get the content we are looking for response = requests.get(url).content print 'response', response # we then send the response back to our client which sent the initial post request return response
def SearchNearestPharmacy(cls, currentLocation: Dict, range: int, limit: int) -> tuple: if not {"latitude", "longitude"} <= currentLocation.keys(): return { "message": "Validation error: currentLocation must contain 'latitude' and 'longitude'" }, 422 uri = env("DATA_URL") try: res = requests.get(uri, timeout=1) except requests.ConnectionError: logger.error("Connection error") return {"message": "Connection Error"}, 503 except Exception as e: logger.error(str(e)) return {"message": str(e)}, 500 if res.status_code != 200: logger.error(res.status_code) return {"message": "Service error"}, res.status_code data = res.json()['features'] pharmacies_distance = [] for key, pharmacy in enumerate(data): coordinates = pharmacy['geometry']['coordinates'] pharmacy_name = pharmacy['properties']['Descrizione'] distance = utils.haversine_distance(currentLocation['latitude'], currentLocation['longitude'], coordinates[1], coordinates[0]) if distance <= range: pharmacies_distance.append({ "name": pharmacy_name, "distance": distance, "location": { "latitude": coordinates[1], "longitude": coordinates[0] } }) if len(pharmacies_distance) == 0: return "No resources", 404 sorted_pharmacies = sorted(pharmacies_distance, key=lambda k: k['distance']) sorted_pharmacies = sorted_pharmacies[:limit] if limit < len( sorted_pharmacies) else sorted_pharmacies return {"pharmacies": sorted_pharmacies}, 200
def create_app(): """ 앱 함수 실행 :return: """ c = env() app = FastAPI() conf_dict = asdict(c) print(conf_dict) db.init_app(app, **conf_dict) app.add_middleware( CORSMiddleware, allow_origins=c.ALLOW_SITE, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.include_router(c_r.router) return app
from aiohttp import web import asyncio import requests import logging import base64 import hashlib import hmac from channel.basic import Basic import settings LINE_CHANNEL_SECRET = settings.env('LINE_CHANNEL_SECRET') LINE_ACCESS_TOKEN = settings.env('LINE_ACCESS_TOKEN') BASE_URL = f'https://api.line.me/v2' DEFAULT_HEADERS = { 'Content-Type': 'application/json', 'Authorization': f'Bearer {LINE_ACCESS_TOKEN}', } class Line(Basic): def __init__(self, bot): super().__init__(bot) def routes(self): # (method, path, handler) return [('POST', '', self.handle)] async def handle(self, request): reply = '?'
def search(self): print 'Services#search', request.form origin = request.form['from'] destination = request.form['dest'] data = { 'origin': origin, 'destination': destination } url = "https://maps.googleapis.com/maps/api/directions/json?"+urlencode(data)+"&sensor=false&key=" + settings.env()['KEY'] print 'url', url # notice this is 'requests' not 'request' # we are using the request modules, 'get' function to send a request from our controller # then we use ".content" to get the content we are looking for response = requests.get(url).content print 'response', response # we then send the response back to our client which sent the initial post request return response
from pathlib import Path import settings import importlib bot_name = settings.env('BOT', default='Echo') bot_module = importlib.import_module(f'bot.{bot_name.lower()}') bot_class = getattr(bot_module, bot_name) bot = bot_class() print(f'{bot_name} bot loaded') print('Press Ctrl+C to quit...\n') print(f'Bot> Hi. What\'s your name?') user_name = input('You> ') bot.set_predicate('name', user_name) reply = bot.reply('Hi') print(f'Bot> {reply}') while True: try: msg = input('You> ') if msg: reply = bot.reply(msg) print(f'Bot> {reply}') except KeyboardInterrupt: print('\nBot> bye!') break
from aiohttp import web import requests import logging import settings from channel.basic import Basic from . import commands SERVER_URL = settings.env('SERVER_URL') BOT_TOKEN = settings.env('TELEGRAM_BOT_TOKEN') BASE_URL = f'https://api.telegram.org/bot{BOT_TOKEN}' class Telegram(Basic): def __init__(self, bot): super().__init__(bot) # check bot token # {"ok":true,"result":{"id":1104292123,"is_bot":true,"first_name":"Bukan Bot","username":"******","can_join_groups":true,"can_read_all_group_messages":false,"supports_inline_queries":false}} res = api_get('getMe') if not res['ok']: raise Exception(f'Invalid BOT_TOKEN: {BOT_TOKEN}') # try to set botPredicate name_tokens = [] data = res['result'] if 'first_name' in data: name_tokens.append(data['first_name']) if 'last_name' in data: name_tokens.append(data['last_name']) if name_tokens:
from selenium.webdriver.firefox.options import Options from settings import env from utils import retry_until_success, is_after_work, has_available_spot, send_message send_message("Bot has started.") while True: start = time() options = Options() options.add_argument("--headless") print("Opening browser") driver = webdriver.Firefox(options=options) driver.implicitly_wait(5) driver.get(env("URL")) driver.find_element_by_css_selector(".one-fourth > a").click() driver.execute_script(""" $('#welcome-window').modal('hide') """) retry_until_success(lambda: driver.find_elements_by_css_selector( '.booking-list > li')[0].click()) sleep(1) for element in driver.find_elements_by_css_selector('.booking-list > li'): if is_after_work(element) and has_available_spot(element): print(element.text.split('\n')[0])
import settings """ Base terminal command manager. Define terminal commands here to run actions """ from flask.ext.script import Manager, Server from flask.ext.sqlalchemy import SQLAlchemy # from flask.ext.migrate import Migrate, MigrateCommand from system.init import initialize_app # from system.init.database import create_database import subprocess import os app = initialize_app() env = settings.env() manager = Manager(app) # implement later, just creates database, needs to have mysql server installed # @manager.option('-db', '--database', help='database name') # def create_db(database): # create_database(app, database) manager.add_command('runserver', Server(host='127.0.0.1')) if __name__ == "__main__": manager.run()
import settings from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base SQLLITE_DB_URL = 'sqlite://' # in memory DB_URL = settings.env('DB_URL', default=SQLLITE_DB_URL) def init_db(): engine = create_engine(DB_URL) Session = sessionmaker() Session.configure(bind=engine) session = Session() Base = declarative_base() return engine, session, Base def create_all(base, engine): base.metadata.create_all(engine) engine, session, Base = init_db()
from aiohttp import web import settings import importlib import logging LOG_LEVEL = settings.env('LOG_LEVEL', default='WARNING') logging.basicConfig(level=getattr(logging, LOG_LEVEL)) async def handle(request): return web.json_response({'message': 'hello world'}) @web.middleware async def error_middleware(request, handler): try: response = await handler(request) return response except Exception as e: body = await request.text() logging.error(body) logging.exception(e) return web.Response(text=str(e), status=500) def channel_routes(): route_map = {} bot_name = settings.env('BOT', default='Echo') bot_module = importlib.import_module(f'bot.{bot_name.lower()}') bot_class = getattr(bot_module, bot_name) bot = bot_class()
except Exception as e: self.error(status_code=500, status_txt="ERROR", data=str(e)) class StatsHandler(BaseHandler): def get(self): self.api_response(_c2dm.get_stats()) if __name__ == "__main__": tornado.options.define("port", default=8888, help="Listen on port", type=int) tornado.options.define("Email", default=None, help="Google client email", type=str) tornado.options.define("Passwd", default=None, help="Google client password", type=str) tornado.options.define("source", default=None, help="C2DM source", type=str) tornado.options.parse_command_line() """ allow sensitive data to be passed on cmd line ( so everyone can see it w ps ) """ for key in ["Email", "Passwd", "source"]: if key in tornado.options.options and tornado.options.options[key].value(): options.get(env())["login"][key] = tornado.options.options[key].value() logging.getLogger().setLevel(settings.get("logging_level")) # the global c2dm _c2dm = c2dm() application = tornado.web.Application( [(r"/push", PushHandler), (r"/stats", StatsHandler), (r"/flush", FlushHandler)], debug=(env() == "dev") ) application.listen(tornado.options.options.port) tornado.ioloop.IOLoop.instance().start()
import aiml import os import logging import settings from bot.base import Base LOG_LEVEL = settings.env('LOG_LEVEL', default='WARNING') logging.basicConfig(level=getattr(logging, LOG_LEVEL)) CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) NAME = 'Bukan' GENDER = 'Male' AIML_FILE = os.path.join(CURRENT_DIR, 'aiml', 'std-startup.xml') AIML_LOAD_CMD = 'load aiml b' class Bukan(Base): def __init__(self): k = aiml.Kernel() k.learn(AIML_FILE) k.respond(AIML_LOAD_CMD) k.setBotPredicate('name', NAME) k.setBotPredicate('gender', GENDER) self.k = k def reply(self, msg: str, user_id: str = None): session_id = self.k._globalSessionID if user_id: self.k._addSession(user_id) session_id = user_id
class StatsHandler(BaseHandler): def get(self): self.api_response(_smtp.get_stats()) if __name__ == "__main__": tornado.options.define("port", default=8888, help="Listen on port", type=int) tornado.options.define("smtphost", default=None, help="smtp host", type=str) tornado.options.define("smtpport", default=25, help="smtp port", type=int) tornado.options.define("usetls", default=True, help="use TLS", type=bool) tornado.options.define("user", default=None, help="smtp user", type=str) tornado.options.define("password", default=None, help="smtp password", type=str) tornado.options.parse_command_line() ''' allow sensitive data to be passed on cmd line ( so everyone can see it w ps ) ''' for key in ['smtphost', 'smtpport', 'user', 'password']: if key in tornado.options.options and tornado.options.options[key].value(): options.get(env())[key] = tornado.options.options[key].value() logging.getLogger().setLevel(settings.get('logging_level')) _smtp = smtprelay(settings.get("smtphost"), settings.get("smtpport"), settings.get("user"), settings.get("password"), usetls=settings.get("usetls")) application = tornado.web.Application([ (r"/push", PushHandler), (r"/stats", StatsHandler), ], debug=(env() == 'dev')) application.listen(tornado.options.options.port) tornado.ioloop.IOLoop.instance().start()
def publish_medias(): # collect all the information in order to publish the medias job_id = request.form['job_id'] job = _get_job(job_id) lead = job.lead.get() listing = lead.listing.get() if lead.sender_broker is None: pprint.pprint('There is nothing to process.') return '', 200 broker = lead.sender_broker.get() agency = broker.agency.get() external_id = listing.external_id fake_id = 666 pprint.pprint('========= BACKGROUND PROCESSING ') pprint.pprint('Source Application: %s' % agency.source_application) pprint.pprint('Listing Id: %s' % external_id) # if we cannot publish the medias, skip it if settings.env() != 'prod' or external_id is None: pprint.pprint('Publishing is not active in this environment yet.') else: x = 1 # iterates over all videos for v in job.medias['videos']: # export to valuegaia if external_id != fake_id: # todo: refactor urgent!!!!! # gets the townflix code inside the url sent by townflix k = v['url'].split('/') townflix_code = k[len(k)-1] # inserts the video at valuegaia valuegaia.insert_video(external_id, townflix_code, v['thumbnail']) # iterates over all photos for p in job.medias['photos']: featured = 'False' if x == 1: featured = 'True' # if valuegaia is the source of this job if agency.source_application == 'GAIA': # export to valuegaia if external_id != fake_id: valuegaia.insert_photo(external_id, p['url'], p['title'], featured) else: pprint.pprint('There is no source application for this job') x = x + 1 if external_id != fake_id: # sort photos at valuegaia valuegaia.sort_photos(external_id) create_activity('JOB_PUBLISHED_AT_VALUEGAIA', job=job) # send a message to property owner telling his job is finished _enqueue_job_approved_message(job) # send a message to broker telling his job is finished _enqueue_broker_job_approved_message(job) create_activity('JOB_FINISHED', job=job) # todo: implement a new message to the broker # telling him that new photos and videos has been added to his listing return '', 200