async def challenge(ctx, name: str): """challenge another player to a game of chess""" if len(ctx.message.mentions) > 0: p1 = ctx.message.author p2 = ctx.message.mentions[0] msg = '{0}, {1} challenges you to a game of chess!'.format(p2.mention, p1.mention) msg += '\nSo are you gonna accept like the *fearless grandmaster* you are, or chicken out? :triumph:\n\n' msg += 'chess.com stats:\n' if p1.name not in name_mapping.keys(): msg += '{0} has not connected his chess.com username yet! :open_mouth:\n\n'.format(p1.mention) else: msg += '**' + p1.nick + '**\n' r = get_player_stats(name_mapping[p1.name]) for n in ['bullet','blitz','rapid','daily']: try: rating = r.json['stats']["chess_"+n]['last']['rating'] msg += n+": "+str(rating)+"\n" except Exception: msg += n+": unrated\n" msg += '\n' if p2.name not in name_mapping.keys(): msg += '{0} has not connected his chess.com username yet! :open_mouth:\n\n'.format(p2.mention) else: msg += '**' + p2.nick + '**\n' r = get_player_stats(name_mapping[p2.name]) for n in ['bullet','blitz','rapid','daily']: try: rating = r.json['stats']["chess_"+n]['last']['rating'] msg += n+": "+str(rating)+"\n" except Exception: msg += n+": unrated\n" msg += '\n' await ctx.send(msg) else: await ctx.send("Please tag the player you want to challenge!")
async def chessdotcom(ctx, name: str): """Get chess.com stats and info about this player""" try: if len(ctx.message.mentions) > 0: print(name) print(ctx.message.mentions) if ctx.message.mentions[0].name in name_mapping.keys(): name = name_mapping[ctx.message.mentions[0].name] else: await ctx.send("This user hasn't saved his chess.com username yet!") return r = get_player_stats(name) stat_msg = [] msg = "Chess.com stats for " + name + "\n" for n in ['bullet','blitz','rapid','daily']: try: rating = r.json['stats']["chess_"+n]['last']['rating'] msg += n+": "+str(rating)+"\n" except Exception: msg += n+": unrated\n" await ctx.send(msg) except Exception as e: print("E:" + str(e)) print(Exception) await ctx.send("There is no chess.com user with that username!")
def chessdotcomstats(user1): p1 = user1.strip() ratings = cdc.get_player_stats(p1) stats = dict() modes = ['bullet','blitz','rapid','classical','correspondence'] emojis = [':gun:',':cloud_lightning:',':alarm_clock:',':clock:',':sunny:'] try: if cdc.is_player_online(p1).json['online'] == True: stats['txt'] = ":green_circle: Online Now!\n\n" else: stats['txt'] = ":red_circle: Offline\n\n" except: stats['txt'] = "\n" for i in modes: try: indx = modes.index(i) search = "chess_" + i stats[i] = ratings.json['stats'][search]['last']['rating'] #stats['txt'] += f"{emojis[indx]} {i}: {stats[i]} \n" stats['txt'] += f"{emojis[indx]} {stats[i]} " except: continue try: rush_best = ratings.json['stats']['puzzle_rush']['best']['score'] stats['txt'] += f":jigsaw::cloud_tornado: {rush_best}" finally: return stats
def get_player_rating(username): data = get_player_stats(username).json categories = ['chess_blitz', 'chess_rapid', 'chess_bullet'] for category in categories: print('Category:', category) print(f'Current: {data[category]["last"]["rating"]}') print(f'Best: {data[category]["best"]["rating"]}') print(f'Best: {data[category]["record"]}')
def get_player_rating(username): data = get_player_stats(username).json['stats'] categories = ['chess_blitz', 'chess_bullet', 'chess_rapid'] for category in categories: print('Category:', category) print(f"Current: {data[category]['last']['rating']}") print(f"Best: {data[category]['best']['rating']}") print(f"Record: {data[category]['record']}")
def get_player_rating(username): data = get_player_stats(username).json['stats'] # printer.pprint(data) categories = ["chess_blitz", "chess_rapid", "chess_bullet"] for category in categories: print('Category:', category) print(f'Current:{data[category]["last"]["rating"]}') print(f'best:{data[category]["best"]["rating"]}') print(f'record:{data[category]["record"]}')
async def get_player_rating(self, ctx, *, username): await ctx.send("Player Ratings") data = chess.get_player_stats(username).json categories = ['chess_blitz', 'chess_rapid', 'chess_bullet'] for category in categories: await ctx.send('Category:' + str(category)) await ctx.send(f'Current: {data[category]["last"]["rating"]}') await ctx.send(f'Best: {data[category]["best"]["rating"]}') await ctx.send(f'Record: {data[category]["record"]}')
def get_Player_Rating(player): try: data = get_player_stats(player).json categories = ['chess_blitz', 'chess_rapid', 'chess_bullet'] for category in categories: print( f'Current Rating for {player} in {category} is: {data[category]["last"]["rating"]}' ) except: print(f'{player} has no Rating in {category}')
def get_current_player_rating( username): #the function returns the current ratings of the player data = get_player_stats(username).json categories = ['chess_blitz', 'chess_rapid', 'chess_bullet', 'chess_daily'] for category in categories: ratings.append(f'{data[category]["last"]["rating"]}') ratings.append(f'{data["tactics"]["highest"]["rating"]}') ratings.append(f'{data["puzzle_rush"]["best"]["score"]}') return ratings
def get_player_rating(username): #data variable contains the data of the users data = get_player_stats(username) # It gets cateogires categories = ['chess_blitz', 'chess_rapid', 'chess_bullet'] for category in categories: # prints out the info print('Category:', category) print(f'Current: {data[category]["last"]["rating"]}') print(f'Best: {data[category]["best"]["rating"]}') print(f'Best: {data[category]["record"]}')
def get_player_ratings(username): data = get_player_stats(username).json printer.pprint(data) categories = ["chess_blitz", "chess_rapid", "chess_bullet"] for category in categories: print("Category:", category) try: print(f'Current: {data["stats"][category]["last"]["rating"]}') except: print("No Current Value Available") try: print(f'Best: {data["stats"][category]["best"]["rating"]}') except: print("No Best Value Available")
def get_ratings(player): stats = get_player_stats(player).json ret = {} for chess_type in stats: if type(stats[chess_type]) is not dict: continue if 'last' not in stats[chess_type]: continue if 'rating' not in stats[chess_type]['last']: continue rating = stats[chess_type]['last']['rating'] rd = None if 'rd' in stats[chess_type]['last']: rd = stats[chess_type]['last']['rd'] ret[chess_type] = {'rd': rd, 'rating': rating} return ret
def cdc_leaderboard(perf='blitz'): gc = gspread.service_account(filename='google-credentials.json') Book = gc.open('Chess_Tourney') sheet = Book.get_worksheet(0) cell = sheet.find(str('ChessCom Username')) players = sheet.col_values(cell.col)[1:] players2 = [x for x in players if str(x) != ''] leaderboardtxt = f"**Chess.com {perf.title()} Ratings** \n" playerlist = [] word = 'last' word2 = 'rating' perf = f'chess_{perf}' if perf == 'chess_streak': word = 'best' word2 = 'score' perf = 'puzzle_rush' for player in players2: try: ratings = cdc.get_player_stats(player) if ratings.json['stats'][perf][word][word2]: ##add to list of lists rating = ratings.json['stats'][perf][word][word2] playerlist.append([player,rating]) except: continue def getKey(item): return item[1] leaderboard = sorted(playerlist,key=getKey,reverse=True) for i in leaderboard: leaderboardtxt += f"{i[0]}: {i[1]}\n" return leaderboardtxt
def get_player_ratings(username): data = get_player_stats(username).json print(f"Ratings = {data['stats']['chess_blitz']['last']['rating']}")
def getPlayerRating(username): data = get_player_stats(username).json categories = ['chess_blitz', 'chess_bullet', 'chess_rapid'] for category in categories: print(f"{category}: {data['stats'][category]['last']['rating']}")
players = get_country_players(country).json['players'] # para cada jogador do país for i in range(len(players)): # caso o player já tenha sido contabilizado, pule para o próximo if players[i] in ja_contabilizados: print(players[i], "já foi contabilizado! Passando para o próximo!", sep=' ') continue # o try é necessário pra ignorar problemas de conexão try: # todos os dados do jogador atual player_profile_data = get_player_profile(players[i]).json player_stats_data = get_player_stats(players[i]).json # dados do jogador atual que vão pro csv current_player = [] # adicionando os dados na ordem correta current_player.append(player_profile_data['player_id']) current_player.append(player_profile_data['username']) current_player.append(player_profile_data['country'][-2:]) current_player.append(player_profile_data['followers']) current_player.append(player_profile_data['last_online']) current_player.append(player_profile_data['joined']) current_player.append(player_profile_data['is_streamer']) current_player.append(player_profile_data['status']) # como os próximos campos podem ou não existir, eu usarei try except pra cada um deles try:
async def on_message(msg): if msg.author == client.user: return #calling name (bhendi) if msg.content.startswith('bhendi') or msg.content.startswith( 'Bhendi') or msg.content.startswith( 'bdb') or msg.content.startswith('Bdb'): userip = msg.content #movie recommendation if 'rec' in userip: movie_name = userip[userip.index('rec') + 4:] search = movie.search(movie_name) mov_id = 0 for res in search: mov_id = res.id break try: recommend = movie.similar(movie_id=mov_id) if recommend: await msg.channel.send('__PEHLE 10 ICH DIKHAATA__') for r in range(0, min(len(recommend), 10)): title = '**' + recommend[r].title + '**\n' title += to_send(recommend[r].title, recommend[r].release_date) await msg.channel.send(title) else: await msg.channel.send( 'KYA TUTUL PUTUL ! Acchese type kar...') except: await msg.channel.send('Kuch to bhi locha ho gaya') #get details of a celebrity if 'whois' in userip: person_name = userip[userip.index('whois') + 6:] search_res = person.search(person_name, 1) for celeb in search_res: pid = person.details(celeb.id) bio = pid.biography biolist = format_string(bio) biolist = biolist[:biolist.find('.') + 1] name = '**' + pid.name + '**' await msg.channel.send(name) if (biolist): await msg.channel.send(biolist) else: await msg.channel.send('Mereko nahi pata') #get popularity of a movie if 'howis' in userip: movie_name = userip[userip.index('howis') + 6:] try: movie_raw = RottenTomatoesClient.search(term=movie_name, limit=1) movie_json = movie_raw['movies'] movie_detail = movie_json[0] final_detail = 'Release year: ' + str(movie_detail['year']) cast = movie_detail['subline'] cast = cast[:-1] final_detail += '\nStarring: ' + cast final_detail += '\nMeter Class: ' + movie_detail[ 'meterClass'] + '\nMeter Score: ' + str( movie_detail['meterScore']) print(final_detail) await msg.channel.send(final_detail) except: await msg.channel.send( "Pehle mereko yeh samjha ki ... isko samjhana kya hai. Type kar firse kutrya !" ) #display movie poster if 'poster' in userip: baseURL = 'https://image.tmdb.org/t/p/w500' movie_name = userip[userip.index('poster') + 7:] search = movie.search(movie_name) search[0].poster_path = baseURL + search[0].poster_path async with aiohttp.ClientSession() as session: async with session.get(search[0].poster_path) as resp: if resp.status != 200: return await msg.channel.send( 'Poster nahi mila, sorry.') data = io.BytesIO(await resp.read()) await msg.channel.send( file=discord.File(data, 'cool_img.png')) #display popular movies if 'popular' in userip: popular = movie.popular() await msg.channel.send('**POPULAR MOVIES**') for mov in popular: title = mov.title + '\n' title += to_send(mov.title, mov.release_date) await msg.channel.send(title) #get magnet links if 'magnet' in userip: movie_name = userip[userip.index('magnet') + 7:] search = movie.search(movie_name) movie_magnet = search[0].title + '\n' movie_magnet += to_send(search[0].title, search[0].release_date) await msg.channel.send(movie_magnet) #send love if 'gib-pyaar' in userip: msg1 = 'Hey ' + msg.mentions[0].mention.format( msg) + '. I love you <3' await msg.channel.send(msg1) #chess get ratings and record if 'chess' in userip: player_name = userip[userip.index('chess') + 6:] try: player_data = chessdotcom.get_player_stats(player_name) send_string = 'chess.com details for **' + player_name + '** :-\n' keylist = list(player_data.keys()) for key in keylist: if key == "fide": break game_type = key tmp = game_type game_type = game_type.replace('_', ' ') game_type = game_type.capitalize() recent = player_data[key] ans = recent['last']['rating'] trec = recent['record'] send_string += '__' + game_type + '__ : ' + str( ans) + ' (' + str(trec['win']) + 'W--' + str( trec['loss']) + 'L--' + str(trec['draw']) + 'D)\n' await msg.channel.send(send_string) except: await msg.channel.send( "Username as absent as Fischer in Game 2...") #ugly var declaration to check author. will fix later auth = '' def chkfunc(m): authid = m.author.id authid = '<@!' + str(authid) + '>' return authid == auth and m.channel == msg.channel def getscard(scorecard, unames): sboard = discord.Embed(title="BhendiBot's Trivia Scorecard", description="Look who's winnin :heart:", color=0x808080) ranknames = '' scr = '' rank = 1 for name in scorecard: ranknames += str(rank) + '. ' + unames[name] + '\n' scr += str(scorecard[name]) + '\n' rank += 1 sboard.add_field(name="Naam", value=ranknames) sboard.add_field(name="Score", value=scr) return sboard #trivia setup if 'trivia' in userip: data = '' skeys = [] options = [] corrans = {} ca = '' scorecard = {} unames = {} alp = ['A', 'B', 'C', 'D'] with open("trivia_rules.txt", "r") as rls: data += rls.read() await msg.channel.send(data) await asyncio.sleep(8) await msg.channel.send( ">>> Padh liye rules ? Let's jump right into it !") for member in msg.mentions: unames[member.mention.format(msg)] = member.display_name scorecard[member.mention.format(msg)] = 0 skeys = list(scorecard.keys()) tokenURL = 'https://opentdb.com/api_token.php?command=request' trivia_obj = requests.get(tokenURL) trivia_json = trivia_obj.json() token = trivia_json['token'] trivia_amt = "https://opentdb.com/api.php?amount=" quiz_session = requests.get(trivia_amt + str(5 * len(scorecard)) + '&token=' + token) session_json = quiz_session.json() for i in range(0, 5 * len(scorecard)): qs_json = session_json['results'][i] auth = skeys[i % len(scorecard)] toask = ':arrow_forward: **Question ' + str( i // len(scorecard) + 1) + '** for ' + str( skeys[i % len(scorecard)]) + '\n```\n' toask += qs_json['question'] + '\n' options = qs_json['incorrect_answers'] ca = qs_json['correct_answer'] ca = html.unescape(ca) options.append(ca) random.shuffle(options) for j in range(0, len(options)): toask += alp[j] + ') ' + options[j] + '\n' corrans[alp[j].lower()] = options[j] toask += '```\n' toask = html.unescape(toask) toask += '*You have 13 seconds to answer :gun:*' await msg.channel.send(toask) try: answer = await client.wait_for('message', check=chkfunc, timeout=13) except asyncio.TimeoutError: await msg.channel.send('*Time\'s up !*') await asyncio.sleep(3) else: seln = answer.content seln = seln[-1] try: if corrans[seln.lower()] == ca: await msg.channel.send('**SAHI JAWAAB ! :clap: **') key = '<@!' + str(answer.author.id) + '>' scorecard[key] += 3 else: await msg.channel.send( 'Hagg dia ! Correct answer was **' + ca + '**') except: await msg.channel.send('Achese options select kar bc') await asyncio.sleep(2) { tmp: v for tmp, v in sorted(scorecard.items(), key=lambda item: item[1]) } embscard = getscard(scorecard, unames) await msg.channel.send(embed=embscard) #help if 'help' in userip: await msg.channel.send("Help Docs under construction")
import io import smtplib from email.message import EmailMessage from email.utils import make_msgid USERNAME = os.getenv('CHESSNAME') APITOKEN = os.getenv('APITOKEN') EMAIL_ADDRESS = os.getenv('EMAIL_ADDRESS') EMAIL_PASS = os.getenv('EMAIL_PASS') # Get datetime for lastweek lastweek = datetime.now() - timedelta(days=7) year, month = lastweek.year, lastweek.month # Get my chess.com personal stats stats = get_player_stats(USERNAME).json categories = ['chess_bullet', 'chess_blitz', 'chess_rapid', 'chess_daily'] chessdotcom_rankingstring = "" for category in categories: chessdotcom_rankingstring += category[6:] + ": " + str( stats[category]['last']['rating']) + "<br>" chessdotcom_rankingstring += 'puzzle rush: ' + str( stats['puzzle_rush']['best']['score']) + "<br>" # Set up lichess API session session = berserk.TokenSession(APITOKEN) client = berserk.Client(session=session) # Get my lichess personal stats profile = client.account.get()