def __init__(self, reqobj={}): global users, BANLIST self.kind = None self.id = None self.uid = "mockuser" self.username = "******" self.newgame = False self.variantkey = "standard" self.fen = None self.pgn = None self.line = [] self.messageid = None try: for key, value in reqobj.items(): self.__dict__[key] = value except: pe() self.user = User(self.uid) if not (self.uid == "mockuser"): if not (self.uid in users): self.user.getdb() else: self.user = users[self.uid] if self.user.username in BANLIST: print("user banned") self.user.verified = False print("request", self.kind, self.user)
def read_string_from_file(path, default): try: content = codecs.open(path, encoding="utf-8").read() return content except: pe() return default
def deletefile(path): if FILE_VERBOSE: log(f"< deleting file < {path} >", "info") try: os.remove(path) except: pe()
def read_json_from_file(path, default): try: obj = json.load(open(path)) return obj except: pe() return default
def vercode(req): global userscoll, MIN_GAMES, MIN_RATING, EXEMPTLIST #print("verifying code for uid [ {} ]".format(req.tempuid)) user = getuser(req.tempuid) #print(user) if not (user.username in EXEMPTLIST): try: userdata = geturl("https://lichess.org/api/user/{}".format( req.username), asjson=True, verbose=True) print(userdata["perfs"]) atomicperf = userdata["perfs"]["atomic"] if atomicperf["games"] < MIN_GAMES: return req.res( {"kind": "vercodefailed"}, "Verification failed. Your account has less than {} games." .format(MIN_GAMES)) if atomicperf["rating"] < MIN_RATING: return req.res( {"kind": "vercodefailed"}, "Verification failed. Your atomic rating is less than {}.". format(MIN_RATING)) except: pe() return req.res( {"kind": "vercodefailed"}, "Verification failed. You dont't seem to be an atomic player.") else: print("user in exemptlist", EXEMPTLIST) profile = geturl("https://lichess.org/@/{}".format(req.username), verbose=True) verified = user.code in profile if verified: sameusers = userscoll.where("username", "==", user.username).get() for doc in sameusers: data = doc.to_dict() #print("user doc already exists", data) user = User(data["uid"]).fromdata(data) break user.setverified(verified) user.setdb() req.uid = user.uid return req.res({ "kind": "codeverified", "verified": verified, "user": user.__dict__ })
def geturljson(url, headers={}): try: content = geturl(url, headers) obj = json.loads(content) except: pe() obj = None return obj
def geturl(url, headers={}, encoding="utf-8"): try: r = http.request("GET", url, headers=headers) content = r.data.decode(encoding) except: pe() content = None return content
def jsonapi(reqobj): req = Req(reqobj) try: resobj = eval(f"{req.kind}(req)") except: pe() resobj = {"kind": "unknownapirequest"} return req.res(resobj)
def convertemots(self, msg): try: for emot, emotcode in self.emotcodes.items(): msg = msg.replace(emot, emotcode.decode('unicode-escape')) except: pe() print("could not convert emot codes") return msg
def gamesreachedhandler(self, numgames): try: print("reporting games reached") sep = int(numgames / 50) * "#firework" self.say( "{} wow, {} games played already in the tourney {}".format( sep, translate(numgames, "bold-sans"), sep)) except: pe() print("could not report games reached")
def write_json_to_fdb(path, obj, writeremote=True): assertlocalfdbpath(path) write_json_to_file(localfdbpath(path), obj) if writeremote: #print("setting remote", path) try: fdb.reference(path).set(json.dumps(obj)) except: pe() print("there was a problem setting remote")
def querystandings(tid, page=1, partial="true"): try: resjson = geturljson( lichess.tourneystandingsurl(tid, page, partial), headers={"Accept": "application/vnd.lichess.v3+json"}) return resjson except: print("could not get standings for {}".format(tid)) pe() return None
def serverlogic(reqobj): req = Req(reqobj) #print(req) if req.kind: try: return eval("{}(req)".format(req.kind)) except: pe() return ({"kind": "servererror"}) return ({"kind": "unknownrequest"})
def dir_listing_as_list(path): try: listing = [] for name in os.listdir(path): currpath = os.path.join(path, name) stats = os.stat(currpath) isdir = os.path.isdir(currpath) listing.append(os_stats_as_dict(stats, name, isdir)) return listing except: pe() return []
def edit_songhuodan(request,songhuodan_id): try: print 'in........' # para = request.POST songhuodan_id = int(songhuodan_id) shd = Songhuodan.objects.get(id=songhuodan_id) chanpin_list = Chanpin.objects.filter(songhuodan=shd).order_by('xuhao') kehu = Kehu.objects.get(id=shd.kehu_id) zongjine = sum([x.jine for x in chanpin_list]) zongshuliang = sum([x.shuliang for x in chanpin_list]) return render(request, 'excels/shd.html', locals()) except: print pe()
def delete_chanpin(request): try: para = request.POST chanpin_id = int(para['chanpin_id']) del_cp = Chanpin.objects.get(id=chanpin_id) up_cp = Chanpin.objects.filter(songhuodan_id=del_cp.songhuodan_id).order_by('id') for i in xrange(len(up_cp)): up_cp[i].xuhao=i up_cp[i].save() del_cp.delete() con_dict = { 'result':'OK' } return HttpResponse(json.dumps(con_dict)) except: print pe()
def createdir(path, createall=True): if os.path.isdir(path): if FILE_VERBOSE: log(f"< < {path} > already exists >", "warning") return True try: if createall: os.makedirs(path) else: os.mkdir(path) if FILE_VERBOSE: log(f"< < {path} > created >", "success") return True except: pe() if FILE_VERBOSE: log(f"< < {path} > could not be created >", "error") return False
def add_kehu(request): try: para = request.POST if Kehu.objects.filter(mingcheng=para['n_kehu_mingcheng']).exists(): con_dict = { 'result':'NG', 'reason':'exists!!!' } else: Kehu.objects.create(mingcheng=para['n_kehu_mingcheng'], dizhi=para['n_kehu_dizhi'], lianxiren=para['n_kehu_lianxiren'], dianhua=para['n_kehu_dianhua']) con_dict = { 'result':'OK' } return HttpResponse(json.dumps(con_dict)) except: print pe()
def add_songhuodan(request): try: tod = datetime.today() time_str = str(tod.year) + ('0'+str(tod.month))[-2:] + ('0'+str(tod.day))[-2:] if Songhuodan.objects.filter(danhao__startswith=time_str).exists(): danhao_base = str(Songhuodan.objects.filter(danhao__startswith=time_str).order_by('danhao').reverse()[0].danhao)[-3:] danhao = time_str + '00' + str(int(danhao_base)+1) else: danhao = time_str + '001' para = request.POST kehu=Kehu.objects.get(id=int(para['kehu_id'])) riqi=str(tod.month)+'/'+str(tod.day)+'/'+str(tod.year) kehudingdanhao=para['kehudingdanhao'] Songhuodan.objects.create(kehu=kehu,danhao=danhao,kehudingdanhao=kehudingdanhao,riqi=riqi) con_dict = { 'result':'OK' } return HttpResponse(json.dumps(con_dict)) except: print pe()
def verify(req): username = req.user.verification["username"] code = req.user.verification["code"] if SERVERLOGIC_VERBOSE: log(f"< verifying user < {username} > code < {code} > >", "info") try: content = geturl("https://lichess.org/@/" + username) if SERVERLOGIC_VERBOSE: log(f"< received content < {len(content)} characters > >", "info") if code in content: if SERVERLOGIC_VERBOSE: log(f"< code found in content >", "success") req.user.username = username req.user.verifiedat = time.time() req.user.verification = None allusers = db.getpath("users") for id, userblob in allusers.items(): if userblob["username"] == username: newuid = userblob["uid"] if SERVERLOGIC_VERBOSE: log( f"< user already exists, changing uid to < {newuid} > >", "warning") req.user.uid = newuid break req.user.storedb() return {"kind": "verified"} except: pe() if SERVERLOGIC_VERBOSE: log(f"< there was a problem verifying user >", "error") if SERVERLOGIC_VERBOSE: log(f"< verification failed >", "error") return { "kind": "verificationfailed", "alert": { "msg": "Verification failed !", "kind": "error" } }
def cron_thread_target(self): ads = [[ "#bluebook #bluebook #bluebook join team Atomic Chess Theoreticians #bluebook #bluebook #bluebook", "https://lichess.org/team/atomic-chess-theoreticians" ], [ "#orangebook #orangebook #orangebook keep track of atomic tourneys #orangebook #orangebook #orangebook", "https://fbserv.herokuapp.com/atomictourneys" ]] maxad = (int(environ.get("MAXADS", len(ads)))) if maxad == 0: print("no ads") return print("max ad", maxad) ads = ads[:maxad] HALF_HOUR = 7200 TICK = 10 RANGE = 3 print("cron started for {}".format(self.tid)) while self.alive: try: now = int(time.time()) halfhourmod = (now % HALF_HOUR) self.halfhourmod = halfhourmod if halfhourmod < (RANGE * TICK): adindex = int((now - halfhourmod) / HALF_HOUR) % len(ads) print("half hour event for {} , ad index {}".format( self.tid, adindex)) for ad in ads[adindex]: self.say(ad) time.sleep(2) time.sleep(TICK * RANGE * 6) except: print("something went wrong with cron") pe() time.sleep(TICK) print("cron terminated for {}".format(self.tid))
def add_chanpin(request): try: para = request.POST shd_id = int(para['songhuodan_id']) shd=Songhuodan.objects.get(id=shd_id) if not Chanpin.objects.filter(songhuodan=shd).exists(): xuhao = 1 else: xuhao = int(Chanpin.objects.filter(songhuodan=shd).order_by('xuhao').reverse()[0].xuhao) + 1 Chanpin.objects.create(xuhao=xuhao, bianhao = para['new_bianhao'], pinmingguige=para['new_pinmingguige'], baozhuang=para['new_baozhuang'], shuliang=int(para['new_shuliang']), danjian=int(para['new_danjia']), jine=int(para['new_shuliang'])*int(para['new_danjia']), shuoming=para['new_shuoming'], songhuodan=shd) con_dict = { 'result':'OK' } return HttpResponse(json.dumps(con_dict)) except: print pe()
* """ thegamepgn_docref.set({"pgn": thegamepgn, "moves": themoves}) else: thegamepgn = thegamepgn_dict["pgn"] themoves = thegamepgn_dict.get("moves", []) print("thegamepgn found", thegamepgn, themoves) thegame = ClientGame("atomic", thegamepgn, None) print("thegame", thegame) storedmessages = getmessages() print("num stored messages", len(storedmessages.keys())) except: pe() print("firebase could not be initialized") ############################################# class Req: def __init__(self, reqobj={}): global users, BANLIST self.kind = None self.id = None self.uid = "mockuser" self.username = "******" self.newgame = False self.variantkey = "standard" self.fen = None
def read_games_thread_target(self): first = True while self.alive: r = requests.get(lichess.gettourneygamesurl(self.tid), headers={"Accept": "application/x-ndjson"}, stream=True) for line in r.iter_lines(): try: line = line.decode("utf-8") gobj = json.loads(line) gid = gobj["id"] status = gobj["status"] if not (status == "started"): if not (gid in self.gameids): self.gameids.append(gid) if (not first): gamesplayed = len(self.gameids) print("{} games played in {}".format( gamesplayed, self.tid)) if (gamesplayed % 200) == 0: print("games played round") self.messagequeue.put( Message("gamesreached", gamesplayed)) players = gobj.get("players", {}) for color in ["white", "black"]: player = players.get(color, {}) rating = player.get("rating", 1500) ratingdiff = player.get("ratingDiff", 0) user = player.get("user", {}) gobj[color + "Name"] = user.get("name") gobj[color + "Rating"] = rating gobj[color + "RatingDiff"] = ratingdiff winner = gobj.get("winner", None) gobj["winner"] = winner gobj["score"] = 0 if winner: if winner == "white": gobj["score"] = 1 else: gobj["score"] = -1 gobj["ratingBias"] = gobj["whiteRating"] - gobj[ "blackRating"] moves = gobj.get("moves", "") if moves == "": gobj["moves"] = [] else: gobj["moves"] = moves.split(" ") self.games[gid] = gobj if (not first): self.messagequeue.put( Message("gamefinished", gid)) else: r.close() break except: if environ.get("LOGGAME", False): pe() pass first = False time.sleep(KEEPALIVE_SLEEP) print("read games thread terminated for {}".format(self.tid))
def couldnotreplyto(self, msg): print("{}could not reply to {}{}".format(ANSI_BRIGHTRED, ANSI_ENDC, msg)) pe()
def playgame(self, event): print("playing game", event) self.playing = True self.ponder = None try: game = event["game"] gameid = game["id"] r = requests.get( f"https://lichess.org//api/bot/game/stream/{gameid}", headers={ "Authorization": f"Bearer {self.token}", "Accept": "application/x-ndjson" }, stream=True) self.gameticks[gameid] = time.time() Thread(target=self.monitorplaygametarget, args=(r, gameid)).start() try: for line in r.iter_lines(): try: line = line.decode("utf-8") self.gameticks[gameid] = time.time() self.lasttick = time.time() event = json.loads(line) kind = event["type"] if kind == "gameFull": self.initialfen = event["initialFen"] self.initialboard = getvariantboard(self.variant) if not (self.initialfen == "startpos"): self.initialboard.set_fen(self.initialfen) self.whiteid = event["white"]["id"] self.blackid = event["black"]["id"] if self.whiteid == self.username.lower(): self.color = chess.WHITE elif self.blackid == self.username.lower(): self.color = chess.BLACK else: print("could not find bot color") break print("game started", self.whiteid, self.blackid, self.color, self.initialfen) if (kind == "gameFull") or (kind == "gameState"): try: if kind == "gameFull": state = event["state"] else: state = event movesstr = state["moves"] moves = [] if len(movesstr) > 0: moves = movesstr.split(" ") board = self.initialboard.copy() for uci in moves: move = chess.Move.from_uci(uci) board.push(move) if board.turn == self.color: bookmove = self.getbookmove(board) if bookmove: print("making book move", bookmove) self.makemove(gameid, bookmove) self.engine.stop() self.ponder = None else: timecontrol = TimeControl( state["wtime"], state["winc"], state["btime"], state["binc"]) (enginemove, ponder) = self.getenginemove( board, self.initialboard, moves, timecontrol, self.ponder) self.ponder = ponder if enginemove: print("making engine move", enginemove, "ponder", ponder) self.makemove(gameid, enginemove) else: print("no engine move") break except: print("probblem processing game state event") pe() except: pass except: print("stream game exception") except: print("problem playing game") print("finished playing game") self.engine.stop() self.playing = False
def gamefinishedhandler(self, gid): try: gobj = self.games[gid] ratingbias = gobj["ratingBias"] score = gobj["score"] nomoves = len(gobj["moves"]) whitename = gobj["whiteName"] whiterating = gobj["whiteRating"] blackname = gobj["blackName"] blackrating = gobj["blackRating"] whitenamelower = whitename.lower() blacknamelower = blackname.lower() if (whitenamelower in self.banlist) or (blacknamelower in self.banlist): self.disturbance() return whiteratedname = "{} ( {} )".format( translate(whitename, "bold-sans"), translate(whiterating, "bold-sans")) blackratedname = "{} ( {} )".format( translate(blackname, "bold-sans"), translate(blackrating, "bold-sans")) rs = ratingbias * score rslimit = (-1) * int(environ.get("RSLIMIT", "200")) effrslimit = rslimit rsfactor = float(environ.get("RSFACTOR", 3)) if score < 0: effrslimit = int(effrslimit / rsfactor) print("{}game finished".format(ANSI_BRIGHTMAGENTA), whitename, whiterating, blackname, blackrating, score, nomoves, rs, effrslimit, self.halfhourmod, ANSI_ENDC) exclam = random.choice([ "what a game", "wow", "unbelievable", "can you believe this", "surprise, surprise" ]) if (rs < effrslimit) and (nomoves > 1): upset = whitename upsetrated = whiteratedname upsetloser = blackname upsetloserrated = blackratedname if score < 0: upset = blackname upsetrated = blackratedname upsetloser = whitename upsetloserrated = whiteratedname gameurl = "https://lichess.org/{}".format(gid) beats = random.choice([ "wins against", "winning against", "defeats", "defeating", "demolishes", "demolishing", "wipes off", "wiping off", "beats", "beating" ]) self.say( random.choice([ "#rocket {} {} {} {}".format(exclam, upsetrated, beats, upsetloserrated), "#rocket {} {} {} {}".format(exclam, upsetrated, beats, upsetloserrated), "#rocket {} {} {} {} points higher rated".format( exclam, upsetrated, beats, translate(abs(ratingbias), "bold-sans")) ])) time.sleep(2) self.say(gameurl) withblack = random.choice([ "#devil with black!", "#devil having the black pieces!", "#devil as black!", "#devil playing black!" ]) if upset == blackname: time.sleep(2) self.say(withblack) time.sleep(2) self.gratulate(translate(upset, "bold-sans")) if ((whiterating - blackrating) > abs(rslimit)) and (score == 0): self.say("#rocket {} {} draws {} with black".format( exclam, blackname, whitename)) time.sleep(2) self.gratulate(translate(blackname, "bold-sans")) except: pe() print("could not handle game finished")