示例#1
0
def paridades():
    api = API()
    api.connect()
    data = request.get_json()
    print(data)
    binary, digital = api.paridades()
    return {'binary': binary, 'digital': digital}
示例#2
0
 def getPlayerData(self, clanID):
     api = API()
     clantag = api.getClanTag(ID)
     players = api.getClanMembers(ID)
     if players is not None:
         for player in players:
             name = api.getPlayerName(player)
示例#3
0
    def updateUserdata(self, userdata, connection, cursor):
        # This updates: LastPlayedDate, Playcount
        embyId = userdata['ItemId']
        MBitem = ReadEmbyDB().getItem(embyId)

        if not MBitem:
            self.logMsg("UPDATE userdata to Kodi library FAILED, Item %s not found on server!" % embyId, 1)
            return

        # Get details
        checksum = API().getChecksum(MBitem)
        userdata = API().getUserData(MBitem)

        # Find the Kodi Id
        cursor.execute("SELECT kodi_id, media_type FROM emby WHERE emby_id = ?", (embyId,))
        try:
            result = cursor.fetchone()
            kodiid = result[0]
            mediatype = result[1]
            self.logMsg("Found embyId: %s in database - kodiId: %s type: %s" % (embyId, kodiid, mediatype), 1)
        except:
            self.logMsg("Id: %s not found in the emby database table." % embyId, 1)
        else:
            if mediatype in ("song"):
                playcount = userdata['PlayCount']
                dateplayed = userdata['LastPlayedDate']

                query = "UPDATE song SET iTimesPlayed = ?, lastplayed = ? WHERE idSong = ?"
                cursor.execute(query, (playcount, dateplayed, kodiid))

                #update the checksum in emby table
                query = "UPDATE emby SET checksum = ? WHERE emby_id = ?"
                cursor.execute(query, (checksum, embyId))
示例#4
0
 def run_API(self):
     api = API(
         host=self.__host,
         port=self.__port,
         key=self.__key,
         moni_port=self.__moni_port)
     api.run()
示例#5
0
    def saveExpValues(self):
        dt = Data()
        api = API()

        temp = api.expectedValues()
        time = temp['time']

        out = []
        for shipid, shipdata in temp['data'].items():
            lst = []
            lst.append(shipid)
            print(
                shipid
            )  #this function takes a while so print ship ID's to keep us occupied. The dark is scary
            #print(shipdata)
            name = api.getShipName(shipid)
            if name is None:
                lst.append("None")
            else:
                lst.append(name)
            if (len(shipdata) != 0):
                lst.append(shipdata['average_damage_dealt'])
                lst.append(shipdata['average_frags'])
                lst.append(shipdata['win_rate'])
            out.append(lst)

        #print(out)
        dt.write('wowsnumbers', (str(time) + '.csv').strip(), out)
        return temp['data']
示例#6
0
    def setListItemProps(self, server, id, listItem, result):
        # set up item and item info
        thumbID = id
        eppNum = -1
        seasonNum = -1
        tvshowTitle = ""
        
        if(result.get("Type") == "Episode"):
            thumbID = result.get("SeriesId")
            seasonNum = result.get("ParentIndexNumber")
            eppNum = result.get("IndexNumber")
            tvshowTitle = result.get("SeriesName")
            
        self.setArt(listItem,'poster', API().getArtwork(result, "Primary"))
        self.setArt(listItem,'tvshow.poster', API().getArtwork(result, "SeriesPrimary"))
        self.setArt(listItem,'clearart', API().getArtwork(result, "Art"))
        self.setArt(listItem,'tvshow.clearart', API().getArtwork(result, "Art"))    
        self.setArt(listItem,'clearlogo', API().getArtwork(result, "Logo"))
        self.setArt(listItem,'tvshow.clearlogo', API().getArtwork(result, "Logo"))    
        self.setArt(listItem,'discart', API().getArtwork(result, "Disc"))  
        self.setArt(listItem,'fanart_image', API().getArtwork(result, "Backdrop"))
        self.setArt(listItem,'landscape', API().getArtwork(result, "Thumb"))   
        
        listItem.setProperty('IsPlayable', 'true')
        listItem.setProperty('IsFolder', 'false')
        
        # Process Studios
        studios = API().getStudios(result)
        if studios == []:
            studio = ""
        else:
            studio = studios[0]
        listItem.setInfo('video', {'studio' : studio})    
            
        details = {
                 'title'        : result.get("Name", "Missing Name"),
                 'plot'         : result.get("Overview")
                 }
                 
        if(eppNum > -1):
            details["episode"] = str(eppNum)
            
        if(seasonNum > -1):
            details["season"] = str(seasonNum)  

        if tvshowTitle != None:
            details["TVShowTitle"] = tvshowTitle    
        
        listItem.setInfo( "Video", infoLabels=details )

        people = API().getPeople(result)

        # Process Genres
        genre = API().getGenre(result)
        
        listItem.setInfo('video', {'director' : people.get('Director')})
        listItem.setInfo('video', {'writer' : people.get('Writer')})
        listItem.setInfo('video', {'mpaa': result.get("OfficialRating")})
        listItem.setInfo('video', {'genre': API().getGenre(result)})
示例#7
0
    def execute(self):
        '''
            Make some actions according to the command
        '''

        if '/start' in self.command:
            API.send_message(
                chat_id=self.chat_id,
                message=START_MESSAGE
            )
示例#8
0
 def getClanData(self, clanID):
     api = API()
     clantag = str(api.getClanTag(clanID))
     temp = d.getMostRecent(clantag)
     tempdata = d.read(clantag, str(temp))
     data = []
     for i in tempdata:
         val = float(i[0])
         data.append(val)
     return data
示例#9
0
 def display_task(self, id=None):
     tmpl = lookup.get_template("display_task.html.mako")
     
     task = API.get_task_object(id)
     if task.parent_job == None:
         job = None
     else:
         job = API.get_job_object(id=str(task.parent_job))
         
     return tmpl.render(task=task, job=job)
示例#10
0
def register_commands(api: API):
    my = api.group(name="my")
    all = api.group(name='all')
    next = api.group(name='next')

    @all.command()
    async def commands(ctx):
        thing_to_display = []
        for command_name, command in ctx.api.commands.items():
            if isinstance(command, commands_.Command):
                thing_to_display.append(f'!{command_name}')
            else:
                thing_to_display.append(
                    f'!{command_name}[{", ".join(command.sub_commands)}]')

        ctx.api.send_chat_message(
            f"All minigame-related chat commands: {', '.join(thing_to_display)}"
        )

    @api.command(usage="<company> <amount>")
    async def buy(ctx, company: CompanyOrIntOrAll, amount: CompanyOrIntOrAll):
        amount: Union[Company, int, 'all']
        company: Union[Company, int, 'all']
        if isinstance(company, Company) and not isinstance(amount, Company):
            pass
        elif not isinstance(company, Company) and isinstance(amount, Company):
            company, amount = amount, company
        elif isinstance(company, Company) and isinstance(amount, Company):
            # ctx.api.send_chat_message(f"@{ctx.user.name} inputted 2 companies. You need to input a number and a company.")
            ctx.api.send_chat_message(
                ctx.api.get_and_format(ctx, 'buy_or_sell_2_companies'))
            return
        elif not isinstance(company, Company) and not isinstance(
                amount, Company):
            # ctx.api.send_chat_message(f"@{ctx.user.name} didn't input any company. You need to input a number and a company.")
            ctx.api.send_chat_message(
                ctx.api.get_and_format(ctx, 'buy_or_sell_0_companies'))
            return

        points = await ctx.user.points(ctx.api)
        if amount == 'all':
            amount = math.floor(points / company.stock_price)

        if share := ctx.session.query(db.Shares).get(
            (ctx.user.id, company.id)):
            stocks_till_100k = 100_000 - share.amount
            if stocks_till_100k == 0:
                ctx.api.send_chat_message(
                    ctx.api.get_and_format(ctx,
                                           'reached_stocks_limit',
                                           company_abbv=company.abbv))
                return
            amount = min(amount, stocks_till_100k)
        else:
示例#11
0
    def Init(self, teams):
        for team in teams:
            self.add_team(team)

        # рандомим места для баз, размещаем их там и инициализируем
        coord_for_bases = sample(self.obj_by_coord, len(teams))
        for base, coord in zip(self.teams_by_base, coord_for_bases):
            API_for_setup = API(world=self)
            API_for_setup.Init(base)
            base.Init(API=API_for_setup)
            self.set_obj(obj=base, coord=coord)
示例#12
0
    def __init__(self):
        
        self.status = SS.startup
        self.file(SE.notify, "Initalizing MCO...")

        # Configuration
        self.file(SE.notify, "Loading configuration")
        self.config = Config('./config/config.json', defaultConfig)

        # Controller
        self.file(SE.notify, "Loading controller")
        self.controller = Config('./config/controller.json', defaultController)

        # Set refresh rate
        self.sleepPerCycle = 1/self.config.get("refreshesPerSecond")

        # LogMonitor
        self.file(SE.notify, "Loading log monitor")
        self.logger = LogMonitor(
            self.config.get("logFolder"), 
            self.config.get("ownUsername"), 
            self.config.get("debug")["Logs"]
        )
        self.status = SS.oldLogs
        self.file(SE.notify, "Loading old logs (if any)")
        self.logger.tick(True)
        self.logger.tick(True)
        self.logger.resetExposed()
        self.status = SS.startup
        self.file(SE.notify, "Loaded old logs")

        # API
        self.file(SE.notify, "Loading API")
        self.api = API(
            self.config.get("token"), 
            int(self.config.get("threads")) - 1,
            self.config.get("debug")["API"]
        )

        self.api.printHypixelStats()
        self.api.printMinecraftStats()

        # CommandSender
        self.file(SE.notify, "Loading Command Sender")
        self.commandSender = CommandSender(self.config.get("commandCooldown"))

        # Init GUI
        self.file(SE.notify, "Loading GUI")
        #self.GUI = GUI(800, 600, "1.0", ["a", "b", "c"], {})
        #self.GUI = GUI()
        # Update status
        self.status = SS.waiting
        self.file(SE.notify, "Finished initializing")
示例#13
0
 def add_task(self, id=None, name=None, state=None, tag=None, dependency=None, parent_job=None, removed_parent_defaults=None,
              image=None, command=None, entrypoint=None, cron=None, restartable=None, exitcodes=None, max_failures=None, delay=None,
             faildelay=None, environment=None, datavolumes=None, port=None, description=None):
     """ """
     if id:
         return API.update_task(id=id, name=name, state=state, tag=tag, dependency=dependency, parent_job=parent_job, removed_parent_defaults=removed_parent_defaults,
                                image=image, command=command, entrypoint=entrypoint, cron=cron, restartable=restartable, exitcodes=exitcodes, max_failures=max_failures, delay=delay, faildelay=faildelay,
                                environment=environment, datavolumes=datavolumes, port=port, description=description)
     else:
         return API.add_task(name=name, state=state, tag=tag, dependency=dependency, parent_job=parent_job, removed_parent_defaults=removed_parent_defaults,
                             image=image, command=command, entrypoint=entrypoint, cron=cron, restartable=restartable, exitcodes=exitcodes, max_failures=max_failures, delay=delay, faildelay=faildelay,
                             environment=environment, datavolumes=datavolumes, port=port, description=description)
示例#14
0
 def run(self):
     # Instancia del juego
     self.size()
     api = API(self.sizev)
     sudoku = Sudoku(api.Table(), self.sizev)
     while not sudoku.is_over():
         print(sudoku.showTable())
         check, error_message = sudoku.playing(self.getValues())
         if not check:
             print(error_message)
     print("\n\nFelicitaciones!!!!")
     print("Terminaste el juego de Sudoku\n\n")
     print(sudoku.showTable())
示例#15
0
 def advance(self):
     '''Ход планеты, он же игровой день'''
     self.repaint_method_by_obj.clear()
     for team in self.teams_by_base.itervalues():
         team.base.advance()
         for ant in team.ants_set:
             dst_coord, move = ant.move()
             my_API = API(world=self)
             if dist(dst_coord, my_API.get_coord_by_obj(ant)) <= 1:
                 getattr(self, move)(dst_coord, ant)
             
     # срабатывает, если при запуске был задан флаг --logs
     self.dump()
示例#16
0
    def Init(self, teams):
        for team in teams:
            self.add_team(team)

        # рандомим места для баз, размещаем их там и инициализируем
        coord_for_bases = sample(self.obj_by_coord, len(teams))
        for base, coord in zip(self.teams_by_base, coord_for_bases):
            API_for_setup = API(world=self)
            if API_for_setup.get_type_by_coord(coord) != type(None):
                self.del_obj(self.obj_by_coord[coord])
            API_for_setup.Init(base)            
            base.Init(API=API_for_setup)
            self.set_obj(obj=base, coord=coord)
示例#17
0
async def postValues(clanname,start,end):
    start_time=time.time()
    embed = discord.Embed()
    #TODO: Check member size to determine if multiple embeds are required
    p = Post()
    a = API()
    u = Util()

    embed = p.createEmbed(clanname,embed,start,end)
    postname = "["+str(clanname)+"] "+a.getClanName(a.getClanID(clanname))+" Statistics"
    embed.set_author(name=postname, icon_url=client.user.default_avatar_url)
    runtime = "Runtime: "+str(u.round3(time.time()-start_time))+" Seconds"
    embed.set_footer(text=str(runtime))
    return embed
 def __init__(self, farmwarename):
     self.farmwarename = farmwarename
     self.input_sequence_init_dic = {}
     self.input_sequence_beforemove_dic = {}
     self.input_sequence_aftermove_dic = {}
     self.input_sequence_end_dic = {}
     self.input_title = get_config_value(self.farmwarename,
                                         'title',
                                         value_type=str)
     self.input_filter_min_x = get_config_value(self.farmwarename,
                                                'filter_min_x',
                                                value_type=str)
     self.input_filter_max_x = get_config_value(self.farmwarename,
                                                'filter_max_x',
                                                value_type=str)
     self.input_filter_min_y = get_config_value(self.farmwarename,
                                                'filter_min_y',
                                                value_type=str)
     self.input_filter_max_y = get_config_value(self.farmwarename,
                                                'filter_max_y',
                                                value_type=str)
     self.input_sequence_init = get_config_value(self.farmwarename,
                                                 'sequence_init',
                                                 value_type=str).split(",")
     self.input_sequence_beforemove = get_config_value(
         self.farmwarename, 'sequence_beforemove',
         value_type=str).split(",")
     self.input_sequence_aftermove = get_config_value(
         self.farmwarename, 'sequence_aftermove', value_type=str).split(",")
     self.input_sequence_end = get_config_value(self.farmwarename,
                                                'sequence_end',
                                                value_type=str).split(",")
     self.input_offset_x = get_config_value(self.farmwarename,
                                            'offset_x',
                                            value_type=int)
     self.input_offset_y = get_config_value(self.farmwarename,
                                            'offset_y',
                                            value_type=int)
     self.input_default_z = get_config_value(self.farmwarename,
                                             'default_z',
                                             value_type=int)
     self.input_default_speed = get_config_value(self.farmwarename,
                                                 'default_speed',
                                                 value_type=int)
     self.input_debug = get_config_value(self.farmwarename,
                                         'debug',
                                         value_type=int)
     self.api = API(self.input_debug)
示例#19
0
    def __init__(self, nom=None, url=None, frequence=7):
        self.API = API.getInstance()

        self.pluginDatas = {"chaines": [], "emissions": {}, "fichiers": {}}
        self.pluginOptions = []

        if nom == None:
            logger.warn(
                "DEPRECATED: il faut préciser le nom du plugin au constructeur"
            )
        else:
            self.nom = nom

        if url == None:
            logger.warn(
                "DEPRECATED: il faut préciser l'url du site du plugin au constructeur"
            )
        else:
            self.url = url

        self.frequence = frequence
        path = os.path.expanduser("~")
        self.fichierConfiguration = path + "/.tvdownloader/conf/" + self.nom.replace(
            " ", "_") + ".conf"
        self.fichierCache = path + "/.tvdownloader/cache/" + self.nom.replace(
            " ", "_") + ".cache"
示例#20
0
    def invoeren(self):
        global informatie, verwijderdregels
        self.leegmaken()
        verwijderdregels = []
        film = self.entry_1.get()
        info = API.APIrequest(film)

        if "Movie not found!" in str(info):
            bericht.showerror("Film info", "Dit is geen bestaande film.")
        else:
            for regel in info.items():
                def labels(a):
                    if a in regel:
                        regelnetjes = str(regel).replace("(","").replace("'","").replace(")","").replace(",",":")
                        informatie = Label(self._master, text=regelnetjes, bg="white",font=("Helvetica", 16))
                        informatie.pack(anchor=W)
                        verwijderdregels.append(informatie)
                labels("Title")
                labels("Actors")
                labels("Plot")
                labels("Director")
                labels("Language")
                labels("imdbRating")
                labels("Released")
                labels("Genre")
                labels("Runtime")
                labels("Year")
示例#21
0
    def addPlaylistItem(self, playlist, item):

        id = item['Id']
        username = utils.window('currUser')
        server = utils.window('server%s' % username)

        playurl = PlayUtils().getPlayUrl(server, id, item)

        if utils.window('playurlFalse') == "true":
            # Playurl failed - set in PlayUtils.py
            utils.window('playurlFalse', clear=True)
            self.logMsg(
                "Failed to retrieve the playback path/url or dialog was cancelled.",
                1)
            return

        self.logMsg("Playurl: %s" % playurl)

        thumb = API().getArtwork(item, "Primary")
        listItem = xbmcgui.ListItem(path=playurl,
                                    iconImage=thumb,
                                    thumbnailImage=thumb)
        self.setListItemProps(server, id, listItem, item)
        self.setProperties(playurl, item, listItem)

        playlist.add(playurl, listItem)
示例#22
0
    def setListItemProps(self, server, id, listItem, result):
        # Set up item and item info
        api = self.api

        type = result.get('Type')
        people = api.getPeople(result)
        studios = api.getStudios(result)

        metadata = {
            'title': result.get('Name', "Missing name"),
            'year': result.get('ProductionYear'),
            'plot': api.getOverview(result),
            'director': people.get('Director'),
            'writer': people.get('Writer'),
            'mpaa': api.getMpaa(result),
            'genre': api.getGenre(result),
            'studio': " / ".join(studios),
            'aired': api.getPremiereDate(result),
            'rating': result.get('CommunityRating'),
            'votes': result.get('VoteCount')
        }

        if "Episode" in type:
            # Only for tv shows
            thumbId = result.get('SeriesId')
            season = result.get('ParentIndexNumber', -1)
            episode = result.get('IndexNumber', -1)
            show = result.get('SeriesName', "")

            metadata['TVShowTitle'] = show
            metadata['season'] = season
            metadata['episode'] = episode

        listItem.setProperty('IsPlayable', 'true')
        listItem.setProperty('IsFolder', 'false')
        listItem.setLabel(metadata['title'])
        listItem.setInfo('video', infoLabels=metadata)

        # Set artwork for listitem
        self.setArt(listItem, 'poster', API().getArtwork(result, "Primary"))
        self.setArt(listItem, 'tvshow.poster',
                    API().getArtwork(result, "SeriesPrimary"))
        self.setArt(listItem, 'clearart', API().getArtwork(result, "Art"))
        self.setArt(listItem, 'tvshow.clearart',
                    API().getArtwork(result, "Art"))
        self.setArt(listItem, 'clearlogo', API().getArtwork(result, "Logo"))
        self.setArt(listItem, 'tvshow.clearlogo',
                    API().getArtwork(result, "Logo"))
        self.setArt(listItem, 'discart', API().getArtwork(result, "Disc"))
        self.setArt(listItem, 'fanart_image',
                    API().getArtwork(result, "Backdrop"))
        self.setArt(listItem, 'landscape', API().getArtwork(result, "Thumb"))
示例#23
0
    def __init__(self):
        # Initialize variables to None
        self.host = None
        self.port = None
        self.chan = None
        self.nick = None
        self.auth = None
        capability = ["tags"]
        self.access_token = None
        self.cooldown = 0
        self.last_command_time = 0
        self.allowed_ranks = []
        self.allowed_users = []
        self.custom_prompt = ""
        with open("blacklist.txt", "r") as f:
            censor = [l.replace("\n", "") for l in f.readlines()]
            self.pf = ProfanityFilter(custom_censor_list=censor)

        # Create an Api instance to connect to AI Dungeon 2.
        logging.debug("Creating API instance.")
        self.api = API(self)

        # Update variables
        logging.debug("Setting settings.")
        Settings(self)

        # Create a Database instance for storing which users do not want to be whispered
        logging.debug("Creating Database instance.")
        self.db = Database(self.chan)

        # Get the session_id
        self.session_id = self.api.get_session_id()

        # Create Websocket object
        logging.debug("Creating TwitchWebsocket object.")
        self.ws = TwitchWebsocket(host=self.host, 
                                  port=self.port,
                                  chan=self.chan,
                                  nick=self.nick,
                                  auth=self.auth,
                                  callback=self.message_handler,
                                  capability=capability,
                                  live=True)
        # Start a blocking websocket connection
        logging.debug("Starting Websocket connection.")
        self.ws.start_bot()
示例#24
0
    def clanReport(self, ID):
        dt = Data()
        api = API()
        ut = Util()
        stats = Stats()

        curtime = ut.getGMTTime()
        clanlist = dt.read('', 'ClanList')
示例#25
0
def process_row(rw):
    logging.debug("process.process_row() start")

    fromdate = rw[0].strip()
    todate = rw[1].strip()
    isin = rw[2].strip()
    transactions = rw[3].strip()
    turnover = rw[4].strip()
    line = 0

    try:
        api = API()  # TODO: Maybe move this up
        sentence = api.handle_response(isin)
        for collection in sentence:
            # Original ESMA values including ISIN
            print(fromdate,
                  ",",
                  todate,
                  ",",
                  isin,
                  ",",
                  transactions,
                  ",",
                  turnover,
                  ",",
                  end="")
            line += 1

            if (sentence == "No identifier found."):
                # This ISIN is unknown, so print "None", and exit loop
                print(
                    "None, None, None, None, None, None, None, None, None, None, None, None, "
                )
                raise Exception(sentence)
            else:
                # Go through received data, and print each line
                for key, valuex in collection.items():
                    value_no_comma = kill_comma(str(valuex))
                    print(value_no_comma, ",", end="")
                print("")

    except Exception as e:
        ex = str(e)
        logging.error(f"Exception: {ex} at line: {line}")

    logging.debug("process.process_row() end")
示例#26
0
 def add_instance_configuration(self, name=None, ami=None, key=None, iam=None, ebssize=None,
                                ebstype=None, userdata=None, instance_type=None, spot=None, bid=None,
                                subnet=None, sg=None, tag=None, id=None, default=False):
     if cherrypy.session.get("usertype", "user") == "admin":
         return API.add_instance_configuration(name, ami, key, iam, ebssize,
                                               ebstype, userdata, instance_type, spot, bid,
                                               subnet, sg, tag, id, default)
     else:
         return json.dumps({"error": "User not authorized for this request"})
示例#27
0
 def __get_apis(self):
     apis = []
     for instance in self.__instances:
         endpoint = "http://" + instance["hostname"] + ":5000"
         host = "bwapi"
         if "API_SERVER_NAME" in instance["env"]:
             host = instance["env"]["API_SERVER_NAME"]
         apis.append(API(endpoint, host=host))
     return apis
示例#28
0
def main():
    # get args
    parser = argparse.ArgumentParser(description='Facial recognition')
    parser.add_argument('--camera',
                        help='Camera device number.',
                        type=int,
                        default=0)
    parser.add_argument('--api', help='Base address for the API')
    parser.add_argument('--frame',
                        help='Picture path if you do not want to use the cam')
    parser.add_argument(
        '--debug',
        help=
        'Boolean if you want to send hardcoded picture to test the server handling',
        action='store_true')

    args = parser.parse_args()
    username = os.environ['wiface_username']
    password = os.environ['wiface_password']
    creds = User(username, password)
    MyAPI = API(creds, args.api)

    if args.debug and args.frame is not None:
        TestWithoutOpenCV(args.frame, MyAPI)
        return

    if args.frame is not None:
        frame = cv.imread(args.frame)
        process_frame(frame, MyAPI)

    else:
        camera_device = args.camera
        # Read the video stream
        cam = cv.VideoCapture(camera_device)
        # setting the buffer size and frames per second, to reduce frames in buffer
        cam.set(cv.CAP_PROP_BUFFERSIZE, 1)
        cam.set(cv.CAP_PROP_FPS, 2)

        if not cam.isOpened:
            print('--(!)Error opening video capture')
            exit(0)

        while True:
            frame = {}
            # calling read() twice as a workaround to clear the buffer.
            cam.read()
            cam.read()
            ret, frame = cam.read()
            if frame is None:
                print('--(!) No captured frame -- Break!')
                break

            process_frame(frame, MyAPI)

        # When everything done, release the capture
        cam.release()
        cv.destroyAllWindows()
示例#29
0
    def action_request(self):
        title = API.get_title_by_id(self.str_input)
        # in this case, pass it in as a list
        self.build_response([title])

        if len(self.response.avail_titles) > 0:
            self.response.message = 'Great! %s is available to stream!' % title.name
        else:
            self.response.message = 'Unfortunately %s is not available to stream.  You might want to set up ' \
                                    'an alert.' % title.name
示例#30
0
 def get_users(self, username=None, userid=None, usertype=None):
     # Check if the user is an admin
     if cherrypy.session.get("usertype", "user") == "admin":
         users = API.get_users(username, userid, usertype)
         if users:
             return [user.json for user in users]
         else:
             return json.dumps({"error": "No user matches the request"})
     else:
         return json.dumps({"error": "User not authorized for this request"})
示例#31
0
 def build_response(self, titles):
     """
     Does the generic parts of building a request. Just provide a list of titles discovered by the subclass's
     implementation of action_request
     """
     titles_with_availability = API.find_titles(titles)
     avail, unavail = self.separate_availability(titles_with_availability)
     self.response = Response()
     self.response.avail_titles = avail
     self.response.unavail_titles = unavail
     self.response.request_type = self.str_type
示例#32
0
 def update_job(
                 self,
                 id=None, name=None, description="", tags=None, state=None, dependencies=None,
                 parent_job=None, command="", entrypoint="", exitcodes="",
                 restartable=True, datavolumes=None, environment=None, image=None, cron="",
                 max_failures=3, delay=0, faildelay=5, port=None
               ):
     return API.update_job(
                             id, name, description, tags, state, dependencies, parent_job, command,
                             entrypoint, exitcodes, restartable, datavolumes, environment, image, cron,
                             max_failures, delay, faildelay, port
                           )
示例#33
0
def ML():

    tfidfconverter = load("tfidfconverter.joblib")
    sentiment_regression_classifier = load(
        "sentiment_regression_classifier.joblib")

    tweet_df = API()
    ##trump_df=pd.read_csv("Trump_tweets_scraped.csv")

    #cleaning up the trump tweets:
    tweet_text = tweet_df['Tweet Text'].to_list()
    edited_text = []
    sentiment_list = []

    #Lowercase tweets
    for tweet in range(0, len(tweet_text)):
        #lower case
        #removing speocial cahracters
        edited_tweet = re.sub(r'\W', ' ', str(tweet_text[tweet]))

        # remove sinflue
        edited_tweet = re.sub(r'\s+[a-zA-Z]\s+', ' ', edited_tweet)

        # Remove single characters from the start
        edited_tweet = re.sub(r'\^[a-zA-Z]\s+', ' ', edited_tweet)

        # Substituting multiple spaces with single space
        edited_tweet = re.sub(r'\s+', ' ', edited_tweet, flags=re.I)

        # Removing prefixed 'b'
        edited_tweet = re.sub(r'^b\s+', '', edited_tweet)

        #removing stopwords tweets

        edited_tweet = edited_tweet.lower()

        edited_text.append(edited_tweet)

        sentiment_trump = sentiment_regression_classifier.predict(
            tfidfconverter.transform([edited_tweet]).toarray())
        sentiment_list.append(sentiment_trump)

    sentiment_list_edited = []

    for item in sentiment_list:
        if "positive" in item:
            sentiment_list_edited.append("positive")
        else:
            sentiment_list_edited.append("negative")

    tweet_df["sentiment"] = sentiment_list_edited

    return tweet_df
示例#34
0
    async def saveExpValues(self):
        dt = Data()
        api = API()

        temp = api.expectedValues()
        time = temp['time']
        #print(temp)
        out = []

        def save(shipid, shipdata):

            lst = []
            lst.append(shipid)
            #print(shipid) #this function takes a while so print ship ID's to keep us occupied. The dark is scary
            #print(shipdata)
            name = api.getShipName(shipid)
            if name is None:
                lst.append("None")
            else:
                lst.append(name)
            if (len(shipdata) != 0):
                lst.append(shipdata['average_damage_dealt'])
                lst.append(shipdata['average_frags'])
                lst.append(shipdata['win_rate'])
            print(lst)
            out.append(lst)

        from concurrent.futures import ThreadPoolExecutor
        executor = ThreadPoolExecutor(max_workers=5)
        loop = asyncio.get_event_loop()

        futures = [
            loop.run_in_executor(executor, save, ship, data)
            for ship, data in temp['data'].items()
        ]
        await asyncio.wait(futures)

        #print(out)
        dt.write('wowsnumbers', (str(time) + '.csv').strip(), out)
        return 0
示例#35
0
    def __init__(self,clan,name):
        #TODO:get Player 'name' Data from WG API
        api = API()
        dt = Data()

        self.playerName=name
        self.playerID=api.getPlayerID(name)

        #TODO:If directory playerclan/playername does not exist and contains no files, then pull data directly from wg api without saving (temp lookup)
        temppath = str(str(clan).strip()+"/"+str(name).strip())
        filestring = dt.getSMostRecent(temppath)
        #print(filestring)
        filestring = filestring.replace("'",'"')
        filestring = filestring.replace("None",'0')
        filestring = filestring.replace("False",'0')
        #print(filestring)
        #print(filestring[189])
        lst = json.loads(filestring)
        print(lst)
        print()

        stats = lst['statistics']
        self.battles = stats['battles']
        self.distance = stats['distance']

        stats = stats['pvp']

        for i in stats:
            print(i)
            print(stats[i])


        for i in lst:
            #print(str(i)+": "+str(lst[i]))
            break
        #print(lst['statistics'])

        #print(Player.calcwr(self.wins,self.losses))
        pass
示例#36
0
    def calcOverallPR(self, playerID):  #player PR calculation
        """
        Parameters:
        playerID: WG player ID

        Returns:
        PR value of player (float)
        """

        a = API()
        d = Data()
        u = Util()

        eDmg = 0
        eWin = 0
        eKil = 0

        aDmg = 0
        aWin = 0
        aKil = 0

        btot = 0

        data = a.getPlayerShipStats(playerID)
        for shipdata in data:
            #print(shipdata)
            b = a.getShipBattles(shipdata)
            id = a.getShipID(shipdata)
            expectedstats = d.getShipStats(id)
            #print(expectedstats)

            if expectedstats is not None:
                eDmg += float(expectedstats[0]) * b
                eKil += float(expectedstats[1]) * b
                eWin += float(expectedstats[2]) * b / 100

                aDmg += a.getShipDmg(shipdata)
                aKil += a.getShipKills(shipdata)
                aWin += a.getShipWins(shipdata)

                btot += b
            #print(b)
            #print(str(aWin))

        dmg = self.PRnormDmg(aDmg, eDmg)
        kills = self.PRnormKil(aKil, eKil)
        wins = self.PRnormWin(aWin, eWin)
        #print(str(dmg)+" "+str(kills)+" "+str(wins))
        return (700 * dmg + 300 * kills + 150 * wins)
示例#37
0
 def updateMusicas(self, event):
     artista = Art.getNome(Art)
     if self.txtUltimaM.get() == "":
         quantidade = 0
     else:
         quantidade = int(self.txtUltimaM.get())
     infoMusicas = API.api_toplyricsUpdate(quantidade)
     toplyrics = TL(infoMusicas)
     self.lstMusicas.delete(0, END)
     i = 0
     while i < int(self.txtUltimaM.get()):
         self.lstMusicas.insert(END, TL.getNome(toplyrics, i))
         i += 1
示例#38
0
    def addPlaylistItem(self, playlist, item, server, userid):

        id = item.get("Id")
        
        playurl = PlayUtils().getPlayUrl(server, id, item)
        utils.logMsg("PlayBackUtils", "Play URL: " + playurl)    
        thumbPath = API().getArtwork(item, "Primary")
        listItem = xbmcgui.ListItem(path=playurl, iconImage=thumbPath, thumbnailImage=thumbPath)
        self.setListItemProps(server, id, listItem, item)

        WINDOW = xbmcgui.Window(10000)

        username = WINDOW.getProperty('currUser')
        userid = WINDOW.getProperty('userId%s' % username)
        server = WINDOW.getProperty('server%s' % username)

        # Can not play virtual items
        if (item.get("LocationType") == "Virtual") or (item.get("IsPlaceHolder") == True):
        
            xbmcgui.Dialog().ok(self.language(30128), self.language(30129))
            return False
            
        else:
        
            watchedurl = "%s/mediabrowser/Users/%s/PlayedItems/%s" % (server, userid, id)
            positionurl = "%s/mediabrowser/Users/%s/PlayingItems/%s" % (server, userid, id)
            deleteurl = "%s/mediabrowser/Items/%s" % (server, id)

            # set the current playing info
            WINDOW = xbmcgui.Window( 10000 )
            WINDOW.setProperty(playurl + "watchedurl", watchedurl)
            WINDOW.setProperty(playurl + "positionurl", positionurl)
            WINDOW.setProperty(playurl + "deleteurl", "")
            
            if item.get("Type") == "Episode" and addon.getSetting("offerDelete")=="true":
               WINDOW.setProperty(playurl + "deleteurl", deleteurl)
        
            WINDOW.setProperty(playurl + "runtimeticks", str(item.get("RunTimeTicks")))
            WINDOW.setProperty(playurl+"type", item.get("Type"))
            WINDOW.setProperty(playurl + "item_id", id)
            
            if (item.get("Type") == "Episode"):
                WINDOW.setProperty(playurl + "refresh_id", item.get("SeriesId"))
            else:
                WINDOW.setProperty(playurl + "refresh_id", id)            
            
            utils.logMsg("PlayBackUtils", "PlayList Item Url : " + str(playurl))
            
            playlist.add(playurl, listItem)
            
            return True
示例#39
0
    def carregarArtista(self, event):
        self.lstMusicas.delete(0, END)
        self.txtUltimaM.delete(0, END)
        if (self.txtArtista.get().strip() == ""):
            ctypes.windll.user32.MessageBoxW(
                0, "Digite o nome de um artista para pesquisar!", "Atenção", 0)
        else:
            """Informações do Artista: Nome, Rank e Generos (se houver). """
            infoArtista = API.api_artista(self.txtArtista.get())
            print(infoArtista)
            Artista = Art(infoArtista)

            self.lblNomeArtista.config(text=Artista.getNome())
            self.lblRank.config(text="Rank Vagalume: " + Artista.getRank())
            self.lblGenero.config(text="Estilo(s): " + Artista.getGenero())

            self.lblNomeArtista.grid()
            self.lblGenero.grid()
            self.lblRank.grid()
            """Informações dos álbums: Nome(se houver) e ano. """
            infoAlbum = API.api_album(self.txtArtista.get())
            Album = Alb(infoAlbum)
            ultimoAlbum = Alb.getNomeAno(Album, 0)

            self.lblUltimoA.config(text="Último álbum: " + ultimoAlbum)
            self.lblUltimoA.grid()

            infoMusicas = API.api_toplyrics(self.txtArtista.get(), 10)
            toplyrics = TL(infoMusicas)
            i = 0
            while i < 10:
                self.lstMusicas.insert(END, TL.getNome(toplyrics, i))
                i += 1
            self.lstMusicas.grid()
            self.lblUltimaM1.grid()
            self.lblUltimaM2.grid()
            self.txtUltimaM.insert(0, "10")
            self.txtUltimaM.grid()
示例#40
0
 def get_log(self, log_name, lines=200, full_log=False):
     if not log_name:
         if full_log:
             return None
         else:
             return '{"error": "log_name must be present"}'
       
     if full_log:
         try:
             return serve_file("/logs/" + log_name, "application/x-download", "attachment")
         except Exception:
             return None
         
     return API.get_log(log_name=log_name, lines=lines)
示例#41
0
    def __init__(self, parent):
        Frame.__init__(self, parent)
        # Initialize the api
        self.api = API()
        # Set the ip and port to communicate with the master server
        self.SERVER_IP = config.masterip
        self.SERVER_PORT = config.port
        # Set the initial server status to 0, will change to 1 if server is active
        # self.serverStatus = 0
        # Declare a list which will hold the files that have been flagged for deletion
        self.toDelete = []

        self.parent = parent
        # Initialize the GUI
        self.initUI()
示例#42
0
 def admin(self):
     # Check if the user is an admin
     if cherrypy.session.get("usertype", "user") == "admin":
         tmpl = lookup.get_template("admin.html.mako")
         if settings['web_use_auth'] == "true":
             return tmpl.render(
                                 username = cherrypy.session['username'],
                                 userimageurl = cherrypy.session['userimageurl'],
                                 usertype = cherrypy.session['usertype'],
                                 settings = settings,
                                 users = API.get_users(),
                                 hooks = API.get_hooks()
                               )
         else:
             return tmpl.render(
                                 username = cherrypy.session.get("username", "dev"),
                                 userimageurl = cherrypy.session.get("userimageurl", "dev"),
                                 usertype = cherrypy.session.get("usertype", "admin"),
                                 settings = settings,
                                 users = API.get_users(),
                                 hooks = API.get_hooks()
                               )
     else:
         return json.dumps({"error": "User not authorized for this request"})
示例#43
0
文件: run.py 项目: ywxkhpt/search
def run(name):
    """
    爬取搜索主函数
    :param name: 搜索的人名
    :return: 爬取的结果
    """
    # 待搜索内容
    KEYWORDS = name

    # 获取账号
    twitter_account = Account()
    t_account = twitter_account.get_account()
    # 登陆账号采集
    Crawler = API(proxy=PROXY, keywords=KEYWORDS)
    result = Crawler.crawler(twitter_account="*****@*****.**",
                             twitter_password="******",
                             host=tweet_host,
                             database=tweet_database,
                             collection=tweet_collection)
    # return Crawler.crawler(twitter_account=t_account[0],
    #                        twitter_password=t_account[1])
    # 将信息存储到数据库
    client = TweetsClient(tweet_host, tweet_database, tweet_collection)
    flag = client.save_to_database(result)
    if flag is True:
        print "插入成功"
        person_website_list = list()
        for item in result:
            person_website = item["screen_name"]
            person_website_list.append(person_website)
        print person_website_list
        data = get_data(screen_name_list=person_website_list)
        return data
    else:
        print "插入失败"
        return None
示例#44
0
    def action_request(self):
        titles = API.get_rss_titles_list(self.str_input)
        self.build_response(titles)

        # set the message according to local rules
        if len(self.response.avail_titles) == 0 and len(self.response.unavail_titles) > 0:
            self.response.message = 'Unfortunately no titles listed at your URL are available to ' \
                                    'stream. You might want to set up an alert, or read the FAQs.'

        elif len(self.response.avail_titles) == 0 and len(self.response.unavail_titles) == 0:
            self.response.message = "We couldn't find any titles at your URL. Please read the FAQs"

        elif len(self.response.avail_titles) > 0 and len(self.response.unavail_titles) == 0:
            self.response.message = 'Great! All titles listed at your URL are available to stream!'

        else:
            self.response.message = 'Great! Some titles listed at your URL are available to stream!'
示例#45
0
    def action_request(self):
        """
        Action a Search request.
        """
        titles = API.match_search_term(self.str_input)
        # titles = [Title('The Martian', 2015, 'movie')]  # OMDb is down!!!
        self.build_response(titles)

        # set the message according to local rules
        if len(self.response.avail_titles) == 0 and len(self.response.unavail_titles) > 0:
            self.response.message = 'Unfortunately no titles matching your search are available to ' \
                                    'stream. You might want to set up an alert, or read the FAQs.'

        elif len(self.response.avail_titles) == 0 and len(self.response.unavail_titles) == 0:
            self.response.message = "We couldn't find any titles matching '%s'." % self.str_input

        elif len(self.response.avail_titles) > 0 and len(self.response.unavail_titles) == 0:
            self.response.message = 'Great! All titles matching your search are available to stream!'

        else:
            self.response.message = 'Great! Some titles matching your search are available to stream!'
示例#46
0
	def __init__(self, nom=None, url=None, frequence=7):
		self.API = API.getInstance()
		
		self.pluginDatas = {"chaines":[],
			"emissions":{},
			"fichiers":{}}
		self.pluginOptions = []
		
		if nom == None:
			logger.warn("DEPRECATED: il faut préciser le nom du plugin au constructeur")
		else:
			self.nom = nom
		
		if url == None:
			logger.warn("DEPRECATED: il faut préciser l'url du site du plugin au constructeur")
		else:
			self.url = url
		
		self.frequence = frequence		
		self.fichierConfiguration = os.path.join( Constantes.REPERTOIRE_CONFIGURATION, self.nom.replace( " ", "_" )+ ".conf" )
		self.fichierCache = os.path.join( Constantes.REPERTOIRE_CACHE, self.nom.replace( " ", "_" ) + ".cache" )
示例#47
0
	def __init__(self, nom=None, url=None, frequence=7):
		self.API = API.getInstance()
		
		self.pluginDatas = {"chaines":[],
			"emissions":{},
			"fichiers":{}}
		self.pluginOptions = []
		
		if nom == None:
			logger.warn("DEPRECATED: il faut préciser le nom du plugin au constructeur")
		else:
			self.nom = nom
		
		if url == None:
			logger.warn("DEPRECATED: il faut préciser l'url du site du plugin au constructeur")
		else:
			self.url = url
		
		self.frequence = frequence
		path = os.path.expanduser( "~" )
		self.fichierConfiguration = path+"/.tvdownloader/conf/"+self.nom.replace( " ", "_" )+".conf"
		self.fichierCache = path+"/.tvdownloader/cache/"+self.nom.replace( " ", "_" )+".cache"
示例#48
0
from OnlineHeart import OnlineHeart
from Silver import Silver
from LotteryResult import LotteryResult
from Tasks import Tasks
from login import Login
from connect import connect
import asyncio
from API import API
login = Login().success()
API.user_info()
API.get_bag_list()
task = OnlineHeart()
task1 = Silver()
task2 = Tasks()
task3 = LotteryResult()
task4 = connect()

tasks = [
    task.run(),
    task1.run(),
    task2.run(),
    task4.connect(),
    task3.query()
]

loop = asyncio.get_event_loop()

loop.run_until_complete(asyncio.wait(tasks))

loop.close()
示例#49
0
 def hook(self, api_token):
     return API.hook(api_token)
示例#50
0
 def enable_hook(self, id):
     if cherrypy.session.get("usertype", "user") == "admin":
         return API.enable_hook(id)
     else:
         return json.dumps({"error": "User not authorized for this request"})
示例#51
0
    def __init__(self):
        # Chargement de la configuration
        with open("config.json", "r") as json_data:
            config = json.load(json_data)
            host = config["host"]
            port = config["port"]
            sleep_time = config["sleepTime"]
            nick = config["nickname"]
            oper_password = config["oper_password"]
            log_file = config["log_file"]
            log_level = config["log_level"]

        logging.basicConfig(filename=log_file,
                            filemode="a",
                            level=getattr(logging, log_level.upper()),
                            format='%(asctime)s [%(levelname)s | %(filename)s > %(funcName)s] %(message)s',
                            datefmt='%x %X')
        stderr = open(log_file, "a")

        logging.info("=== Starting bot ===")
        logging.info("Loading API")
        self.API = API(self)
        logging.info("Loading plugins")
        self.plugins = Plugins(self.API)

        logging.info("Connecting to the IRC network")
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.connect((host, port))
        self.API.send_command("NICK {}".format(nick))
        self.API.send_command("USER {} 0 * :Bot".format(nick))
        while True:
            motd = self.socket.recv(1024).decode()
            if len(motd) > 0:
                for line in motd.splitlines():
                    logging.info(line)
            if "Current Global Users" in motd:
                break

        self.API.send_command("OPER Bot {}".format(oper_password))
        for line in self.socket.recv(1024).decode().splitlines():
            logging.info(line)

        for channel in self.API.get_channels():
            self.API.send_command("JOIN " + channel)
            for line in self.socket.recv(1024).decode().splitlines():
                logging.info(line)
            self.API.send_command("SAMode {} +o {}".format(channel, nick))
            for line in self.socket.recv(1024).decode().splitlines():
                logging.info(line)
            self.API.send_names_query(channel)

        logging.info("Connected !")
        logging.info("Loading plugins")

        self.plugins.load()

        commands = {
            "PING": self.ping,
            "PRIVMSG": self.privmsg,
            "JOIN": self.join,
            "KICK": self.kick,
            "PART": self.part,
            "MODE": self.mode,
            "QUIT": self.quit
        }

        logging.info("Starting main-loop")
        self.API.send_command("PONG :127.0.0.1")
        self.running = True
        while self.running:
            rlist, wlist, xlist = select([self.socket], [], [], sleep_time)
            if rlist:
                try:
                    msg = self.socket.recv(1024).decode()
                except Exception as ex:
                    logging.exception(ex)
                else:
                    for line in msg.splitlines():
                        logging.info(line)
                        args = line.split(" ")
                        if len(args) >= 1 and args[0] in commands:
                            commands[args[0]](args)

                        elif len(args) >= 2 and args[1] in commands:
                            commands[args[1]](args)

                        else:
                            pass

            self.plugins.loop()

        self.socket.close()
示例#52
0
 def stop_job(self, id=None, name=None, username=None, state=""):
     return API.stop_job(id, name, username, state)
示例#53
0
 def get_instance_configurations(self, id=None, name=None):
     return API.get_instance_configurations(id, name)
示例#54
0
 def add_user(self, username, userid, usertype):
     # Check if the user is an admin
     if cherrypy.session.get("usertype", "user") == "admin":
         return API.add_user(username, userid, usertype)
     else:
         return json.dumps({"error": "User not authorized for this request"})
示例#55
0
 def set_setting(self, setting=None, value=None):
     # Check if the user is an admin
     if cherrypy.session.get("usertype", "user") == "admin":
         return API.set_setting(setting, value)
     else:
         return json.dumps({"error": "User not authorized for this request"})
示例#56
0
 def add_incoming_hook(self, name=None, action=None, target=None):
     if cherrypy.session.get("usertype", "user") == "admin":
         return API.add_incoming_hook(name, action, target)
示例#57
0
class Server:
    def __init__(self):
        # Chargement de la configuration
        with open("config.json", "r") as json_data:
            config = json.load(json_data)
            host = config["host"]
            port = config["port"]
            sleep_time = config["sleepTime"]
            nick = config["nickname"]
            oper_password = config["oper_password"]
            log_file = config["log_file"]
            log_level = config["log_level"]

        logging.basicConfig(filename=log_file,
                            filemode="a",
                            level=getattr(logging, log_level.upper()),
                            format='%(asctime)s [%(levelname)s | %(filename)s > %(funcName)s] %(message)s',
                            datefmt='%x %X')
        stderr = open(log_file, "a")

        logging.info("=== Starting bot ===")
        logging.info("Loading API")
        self.API = API(self)
        logging.info("Loading plugins")
        self.plugins = Plugins(self.API)

        logging.info("Connecting to the IRC network")
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.connect((host, port))
        self.API.send_command("NICK {}".format(nick))
        self.API.send_command("USER {} 0 * :Bot".format(nick))
        while True:
            motd = self.socket.recv(1024).decode()
            if len(motd) > 0:
                for line in motd.splitlines():
                    logging.info(line)
            if "Current Global Users" in motd:
                break

        self.API.send_command("OPER Bot {}".format(oper_password))
        for line in self.socket.recv(1024).decode().splitlines():
            logging.info(line)

        for channel in self.API.get_channels():
            self.API.send_command("JOIN " + channel)
            for line in self.socket.recv(1024).decode().splitlines():
                logging.info(line)
            self.API.send_command("SAMode {} +o {}".format(channel, nick))
            for line in self.socket.recv(1024).decode().splitlines():
                logging.info(line)
            self.API.send_names_query(channel)

        logging.info("Connected !")
        logging.info("Loading plugins")

        self.plugins.load()

        commands = {
            "PING": self.ping,
            "PRIVMSG": self.privmsg,
            "JOIN": self.join,
            "KICK": self.kick,
            "PART": self.part,
            "MODE": self.mode,
            "QUIT": self.quit
        }

        logging.info("Starting main-loop")
        self.API.send_command("PONG :127.0.0.1")
        self.running = True
        while self.running:
            rlist, wlist, xlist = select([self.socket], [], [], sleep_time)
            if rlist:
                try:
                    msg = self.socket.recv(1024).decode()
                except Exception as ex:
                    logging.exception(ex)
                else:
                    for line in msg.splitlines():
                        logging.info(line)
                        args = line.split(" ")
                        if len(args) >= 1 and args[0] in commands:
                            commands[args[0]](args)

                        elif len(args) >= 2 and args[1] in commands:
                            commands[args[1]](args)

                        else:
                            pass

            self.plugins.loop()

        self.socket.close()

    def ping(self, args: list) -> None:
        # PING :127.0.0.1
        if len(args) >= 2:
            self.API.send_command("PONG " + args[1])

    def privmsg(self, args: list) -> None:
        if len(args) >= 4:
            # :[email protected] PRIVMSG #Dev :plop
            #  ^^^^^^^^^^^                                                  ^^^^
            sender = args[0][1:args[0].find("!")]  # Julien00859
            channel = args[2]  # #Dev
            if channel in self.API.get_channels():
                self.plugins.public_message(channel, sender, " ".join(args[3:len(args)])[1:])

            elif channel == self.API.get_bot_nick():
                self.plugins.private_message(sender, " ".join(args[3:len(args)])[1:])

    def join(self, args: list) -> None:
        if len(args) >= 3:
            # :[email protected] JOIN :#Dev
            #  ^^^^^^^^^^^                                                ^^^^
            sender = args[0][1:args[0].find("!")]  # Julien00859
            channel = args[2][1:]  # #Dev
            self.API.add_update_user(channel, sender)
            self.plugins.join(channel, sender)

    def kick(self, args: list) -> None:
        # :[email protected] KICK #Dev Julien00859 :You have been kicked
        #  ^^^^^^^^^                                               ^^^^ ^^^^^^^^^^^
        if len(args) >= 4:
            sender = args[0][1:args[0].find("!")]  # Julien008
            self.API.remove_user(args[2], args[3])
            self.plugins.kick(sender, args[2], args[3])

    def part(self, args: list) -> None:
        if len(args) >= 3:
            # :[email protected] PART #Dev :"Gonna bake some cookies..."
            #  ^^^^^^^^^^^                                               ^^^^
            sender = args[0][1:args[0].find("!")]  # Julien00859
            self.API.remove_user(args[2], sender)
            self.plugins.part(args[2], sender)

    def mode(self, args: list) -> None:
        # :[email protected] MODE #Dev +h Julien00859
        #  ^^^^^^^^^                                               ^^^^ ^^ ^^^^^^^^^^^

        sender = args[0][1:args[0].find("!")]  # Julien008
        if len(args) >= 5:
            self.API.send_names_query(args[2])
            self.plugins.mode(sender, args[2], args[3], args[4])

    def quit(self, args: list) -> None:
        if len(args) >= 1:
            # :[email protected] QUIT :Quit: Keep calm and do not rage quit
            #  ^^^^^^^^^^^
            sender = args[0][1:args[0].find("!")]  # Julien00859
            for channel in self.API.get_channels():
                self.API.remove_user(channel, sender)
                self.plugins.quit(sender)
示例#58
0
 def get_hooks(self, id=None, action=None, target=None, state=None, api_token=None):
     return API.get_hooks(id, action, target, state, api_token)
示例#59
0
 def delete_configuration(self, id):
     return API.delete_configuration(id)
示例#60
0
    def login(self, code=None):
        # if the session is already authorized send the user to the main page
        if cherrypy.session.get("authorized", None):
            raise cherrypy.HTTPRedirect("/")

        # if the `code` parameter was POSTed, try to authenticate the user
        if code:
            # First check that the code is valid
            # Query GitHub for an access token for the code
            git_auth = "https://github.com/login/oauth/access_token?" + \
                       "client_id=" + settings['web_github_oauth_id'] + \
                       "&client_secret=" + settings['web_github_oauth_secret'] + \
                       "&code=" + code
            
            req = Request(git_auth)
            res = urlopen(req)
            
            # split the response into a dict
            response = {}
            for param in res.read().decode('utf-8').split("&"):
                response[param.split("=")[0]] = param.split("=")[1]
            
            # Second, get the GitHub acccount information
            # if the code resulted in a valid access token
            if "access_token" in response.keys():
                # Get the user information
                get_info = "https://api.github.com/user?access_token=" + response['access_token']
                req = Request(get_info)
                res = urlopen(req)

                # Parse the resulting JSON
                data = json.loads(res.read().decode('utf-8'))
                
                # if the user is in the authorized user list
                userdata = API.get_users(userid=str(data['id']))
                if userdata:    
                    user_data = userdata[0]
                    if user_data.username == data['login']:
                        # Modify the user session to indicated authorization

                        # store a SHA of the inital request information
                        # if this doesn't match force a new session
                        agent = cherrypy.request.headers['User-Agent']
                        # remote_ip = cherrypy.request.remote.ip
                        print(agent)
                        cherrypy.session["_ident"] = sha256(agent.encode('utf-8')).hexdigest()
                        
                        # Set the expiration time
                        cherrypy.session['expires'] = int(time()) + 1800 # 30 minutes from now

                        # Regenerate the session ID on successful login
                        cherrypy.session.regenerate()
                        
                        # Store user information in the session
                        cherrypy.session["authorized"] = "true"
                        cherrypy.session["userid"] = user_data.userid
                        cherrypy.session["username"] = user_data.username
                        cherrypy.session["usertype"] = user_data.usertype
                        cherrypy.session["userimageurl"] = data['avatar_url']
                        
                        # Send the authorized user to the main page or previous request
                        cherrypy.session["login_msg"] = None
                        redirect = cherrypy.session.get("redirect", "/")
                        raise cherrypy.HTTPRedirect(redirect)
                    
                    else:
                        cherrypy.session["login_msg"] = "Login failed."
                        return "Login failed. User '" + data['login'] + "' is not authorized"
                        
                # The user is not authorized
                else:
                    cherrypy.session["login_msg"] = "Login failed."
                    return "Login failed. User '" + data['login'] + "' is not authorized"

            # The code was not valid or not sent by GitHub
            else:
                cherrypy.session["login_msg"] = "Login failed."
                return "Login failed"

            cherrypy.session["login_msg"] = "Login failed."
            return "There was an error: " + str(response)
        
        # Regenerate the session ID before logging in
        cherrypy.session.regenerate()
        tmpl = lookup.get_template("login.html.mako")
        return tmpl.render(
                            client_id = settings['web_github_oauth_id'],
                            msg = cherrypy.session.get("login_msg", None)
                           )