def __init__(self, config): UserStore.__init__(self, config) logging.basicConfig(level = logging.DEBUG, format = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt = '%m-%d %H:%M') self.logger = logging.getLogger('OIDDBUserStore') self.conn = DBFactory(self.logger, config.source).connect()
def __init__(self, config): UserStore.__init__(self, config) logging.basicConfig( level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M') self.logger = logging.getLogger('OIDDBUserStore') self.conn = DBFactory(self.logger, config.source).connect()
def __init__(self, apiId, apiHash) -> None: self.bot = TelegramClient('CoronaWHVBot', apiId, apiHash) self.bot.add_event_handler(self.onStartMessage, events.NewMessage(pattern="/start")) self.bot.add_event_handler(self.onStopMessage, events.NewMessage(pattern="/stop")) self.bot.add_event_handler(self.onRegionResetMessage, events.NewMessage(pattern="/resetRegion")) self.bot.add_event_handler( self.onRegularMessage, events.NewMessage(pattern="^(?!(/start|/stop|/resetRegion).*$).*")) self.userStore = UserStore() self.dataStoreProvider = RegionSourceProvider()
class CoronaBot(object): def __init__(self, apiId, apiHash) -> None: self.bot = TelegramClient('CoronaWHVBot', apiId, apiHash) self.bot.add_event_handler(self.onStartMessage, events.NewMessage(pattern="/start")) self.bot.add_event_handler(self.onStopMessage, events.NewMessage(pattern="/stop")) self.bot.add_event_handler(self.onRegionResetMessage, events.NewMessage(pattern="/resetRegion")) self.bot.add_event_handler( self.onRegularMessage, events.NewMessage(pattern="^(?!(/start|/stop|/resetRegion).*$).*")) self.userStore = UserStore() self.dataStoreProvider = RegionSourceProvider() def __del__(self): self.stop() async def start(self, token): return await self.bot.start(bot_token=token) async def stop(self): self.userStore.close() asyncio.get_running_loop().run_until_complete(self.bot.disconnect()) print("Bot stoped and database closed") async def onStartMessage(self, event): sender = event.input_sender try: print(self.userStore.getUser(sender.user_id, sender.access_hash)) self.userStore.addUserToDB(sender.user_id, sender.access_hash) print("added user") await event.respond( "Für welches Gebiet willst du jeden Morgen um 09:00 Nachrichten erhalten?\n\nBitte gebe zunächst die Art der Region an!", buttons=getRegionTypeKeyboard()) except Exception as e: await event.respond( "Irgendwas hat nicht funktioniert! Probiere nochmal \"/start\" oder kontaktiere den Admin", buttons=getDisabledKeyboard()) print("adding went wrong", e) async def onStopMessage(self, event): sender = event.input_sender try: self.userStore.removeUserFromDB(sender.user_id, sender.access_hash) print("removed user") await event.respond( "Du wurdest erfolgreich entfernt, du wurst nun keine Nachrichten mehr erhalten!", buttons=getDisabledKeyboard()) except Exception as e: await event.respond( "Das entfernen hat nicht funktioniert. Du wirst weiterhin Nachrichten erhalten!", buttons=getDefaultKeyboard()) print("deleting went wrong!", e) async def onRegionResetMessage(self, event): sender = event.input_sender try: self.userStore.removeRegionOfUser(sender.user_id, sender.access_hash) print("removed user") await event.respond( "Deine Region wurde erfolgreich entfernt. Für welche Region willst du ab jetzt Nachrichten erhalten?\n\nBitte gebe zunächst die Art der Region an!", buttons=getRegionTypeKeyboard()) except Exception as e: await event.respond( "Das entfernen hat nicht funktioniert. Du wirst weiterhin Nachrichten erhalten!", buttons=getDefaultKeyboard()) async def onRegularMessage(self, event): sender = event.input_sender databaseUser = self.userStore.getUser(sender.user_id, sender.access_hash) if (databaseUser[2] == None): await self.tryAddRegionType(event, databaseUser) elif (databaseUser[3] == None): await self.tryAddRegionName(event, databaseUser) else: await event.reply("Ich weiß nicht was ich tun soll!") async def tryAddRegionType(self, event, databaseUser): regionType = event.message.message isRegionType = any( map(lambda b: b.button.text == event.message.message, flatten(getRegionTypeKeyboard()))) if (not isRegionType): await event.respond("Das war kein erlaubte Regionsart!", buttons=getRegionTypeKeyboard()) else: try: self.userStore.setRegionTypeOfUser(databaseUser[0], databaseUser[1], regionType) await event.respond( "Schreibe jetzt bitte den Namen der Region!", buttons=Button.clear()) except Exception as e: print("region type saving failed", e) await event.respond( "Beim Speichern ist etwas schief gelaufen, versuche es nochmal oder kontaktiere den Admin" ) async def tryAddRegionName(self, event, databaseUser): name = event.message.message region = Region(databaseUser[2], None) possibleNames = [ n.lower() for n in self.dataStoreProvider.getPossibleNameForRegionType(region) ] if (name.lower() in possibleNames): await event.respond( "Alles klar, ab jetzt bekommst du jeden Morgen um 09:00 eine Nachricht über die aktuelle Lage!", buttons=getDefaultKeyboard()) self.userStore.setRegionNameOfUser(databaseUser[0], databaseUser[1], name) else: me = "Ich habe diesen Ort nicht gefunden!" bs = Button.clear() closeMatches = list( difflib.get_close_matches(name, possibleNames, n=5)) if (len(closeMatches) > 0): bs = getKeyboardFromList( map(lambda n: n.capitalize(), closeMatches)) me += "\n\nMeinst du vielleicht:\n" for m in closeMatches: me += " - %s\n" % (m.capitalize()) await event.respond(me, buttons=bs) async def sendMessageToAll(self, message): users = self.userStore.getAllActiveUsers() for u in users: peer = InputPeerUser(u[0], u[1]) try: await self.bot.send_message(peer, message, parse_mode="html") except UserIsBlockedError: self.userStore.removeUserFromDB(u[0], u[1]) async def sendUpdateToAll(self): print("Sending Number Update to all users") users = filter(lambda u: u[2] != None and u[3] != None, self.userStore.getAllActiveUsers()) for user in users: peer = InputPeerUser(user[0], user[1]) try: message = getMessage( self.dataStoreProvider.getSourceFromRegion( Region(user[2], user[3]))) try: await self.bot.send_message(peer, message, parse_mode="html") except UserIsBlockedError: self.userStore.removeUserFromDB(user[0], user[1]) except: pass print("all messages send") async def runUntilDisconnect(self): return await self.bot.run_until_disconnected()
self.users.con.end_request() self.write( ret ) self.finish() #def postFinish( self, response ): # self.write( response ) # self.finish() def parseExtensions( self, headers ): ext = [] try: extensions = headers['X-Mining-Extensions'] ext = extensions.split( " " ) except: pass return ext if __name__ == "__main__": from PoolStore import PoolStore from UserStore import UserStore p = PoolStore( "config.json" ) u = UserStore( "config.json" ) application = tornado.web.Application( [ (r"/", GetWorkHandler, dict(sharedb=p, usersdb=u, poolname="mine") ) ], debug=True ) http_server = tornado.httpserver.HTTPServer(application) http_server.listen(8888) tornado.ioloop.IOLoop.instance().start()
""" Create a lot of fake data to enter into the data base """ from random import randint from numpy.random import random_integers from numpy.random import random_sample from UserStore import UserStore from SessionStore import SessionStore from FoodStore import FoodStore from datetime import datetime from RestaurantStore import RestaurantStore sessions = SessionStore( "config.json" ) users = UserStore( "config.json" ) restaurant = RestaurantStore( "config.json" ) foods = FoodStore( "config.json" ) numSessions = 100 menu = restaurant.getMenu( "mGoPS" ) us = users.collection.find() ut = [] for u in us: ut.append( u['uid'] ) for sess in range( numSessions ): us = random_integers( 1, len( ut ) - 1, randint( 1, 5 ) )
return food def getSessionsByRestaurant( self, rid ): sessions = self.collection.find( { "restaurantId": rid } ) ret = [] for s in sessions: s['_id'] = str( s['_id'] ) s['stateDate'] = str( s['stateDate'] ) for i in range( len( s['receipt'] ) ): s['receipt'][i] = str( s['receipt'][i] ) ret.append( s ) return ret if __name__ == "__main__": from UserStore import UserStore s = SessionStore( "config.json" ) u = UserStore( "config.json" ) user = u.getByID( "1234567890" ) sess = s.addSession( "test_session" ) print sess print s.addUser( sess, user['uid'] ) print s.get( sess )
def __init__( self, config ): self.config = Config( config ) self.users = UserStore( config ) self.pools = PoolStore( config, self.users ) self.admins = AdminStore( config ) self.getwork = GetWork( self.pools, self.config['pool']['defaultPool'] ) console = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s: %(name)s - %(levelname)s - %(message)s') console.setFormatter( formatter ) logging.getLogger('').addHandler( console ) LEVELS = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL } #if "logFile" in self.config: # fileHandler = logging.FileHandle( str( self.config['logFile'] ) ) # fileHandler.setFormatter( formatter ) # logging.getLogger('').addHandler( fileHandler ) self.logger = logging.getLogger( "PoolManager" ) try: self.logger.setLevel( LEVELS[self.config['logLevel']] ) except: self.logger.setLevel( logging.ERROR ) self.logger.info( "PoolManager Started" ) self.logger.info( "Creating Tornado Applications" ) self.longpoll = LongPoll( self.pools, "triplemining.com" ) #TODO: Make this configurable self.threadpool = ThreadPool( 20 ) self.getworkApp = tornado.web.Application( [ (r"/", GetWorkHandler ), ( r"/LP", LongPollHandler ) ] ) self.getworkApp.pools = self.pools self.getworkApp.users = self.users self.getworkApp.getwork = self.getwork self.getworkApp.poolname = self.config['pool']['defaultPool'] self.getworkApp.longpoll = self.longpoll self.getworkApp.threadpool = self.threadpool self.logger.info( "Creating HTTPServers for the Web interfave and the pool backend." ) self.getworkServer = tornado.httpserver.HTTPServer(self.getworkApp) settings = { "cookie_secret": base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes), "login_url": "/login" } dowser_app = WSGIContainer( cherrypy.tree.mount( dowser.Root() , '/dowser' ) ) self.frontendApp = tornado.web.Application( [ ( r"/", DefaultHandler ), ( r"/getusers", DefaultHandler ), ( r"/getpools", DefaultHandler ), ( r"/admin(/[\w\d\+%]+)?", AdminHandler ), ( r"/login", LoginHandler ), ( r"/pool/([\w\d\.\+ %]+)", PoolHandler ), (r"/dowser.*", tornado.web.FallbackHandler ) #( r"/memory", MemoryDisplayHandler, dict( hp=self.hp ) ) ], **settings ) self.frontendApp.pools = self.pools self.frontendApp.users = self.users self.frontendApp.admins = self.admins self.frontendApp.getwork = self.getwork self.frontendApp.poolname = self.config['pool']['defaultPool'] self.frontendServer = tornado.httpserver.HTTPServer( self.frontendApp ) self.logger.info( "Pool Running On Port ( %d )", self.config['pool']['port'] ) self.getworkServer.listen( self.config['pool']['port'] ) self.logger.info( "Web Interface Running On Port ( %d )", self.config['http']['port'] ) self.frontendServer.listen( self.config['http']['port'] ) self.logger.info( "Starting IOLoop" ) tornado.ioloop.IOLoop.instance().start()