def commentary(mid): commentory_by_ball = [] c = Cricbuzz() comm = c.commentary(mid) print(json.dumps(comm, indent=4, sort_keys=True)) commentory_by_ball.append(comm) return jsonify({'commentory by Ball': commentory_by_ball})
def squad(mid): """ To display the squad for the individual teams available for the match""" header = ["S.no", "Player"] c = Cricbuzz() game = c.scorecard(mid) try: for i in range(2): my_data = [] squad = game['squad'][i]['members'] sq_team = game['squad'][i]['team'] print(colors("\n--{} Squad--\n".format(sq_team), 32)) counter = 1 for counter, member in enumerate(game['squad'][i]['members'], start=1): my_data.append([counter, member]) print(tabulate(my_data, headers=header, tablefmt="fancy_grid")) print("\n") sleep(1) except KeyError: game = c.commentary(mid) try: for i in range(1, 4): print("\n" + game['commentary'][i]) except (IndexError, KeyError): pass
def commentary(mid): c = Cricbuzz() comm = c.commentary(mid) print(json.dumps(comm, indent=4, sort_keys=True)) # commentary("30415")
def score(): c=Cricbuzz() matches=c.matches() post_id1=request.form.get('live score') post_id2=request.form.get('commentary') post_id3=request.form.get('scorecard') if post_id1 is not None: #print(matches) x=[] cnt=0 for match in matches: x.append(json.dumps(c.livescore(match['id']),indent=4)) cnt+=1 q=1 return render_template('score.html',y=x,count=cnt,id=q) if post_id2 is not None: x=[] cnt=0 for match in matches: x.append(json.dumps(c.commentary(match['id']),indent=4)) cnt+=1 q=2 return render_template('score.html',y=x,count=cnt,id=q) if post_id3 is not None: x=[] cnt=0 for match in matches: x.append(json.dumps(c.livescore(match['id']),indent=4)) cnt+=1 q=3 return render_template('score.html',y=x,count=cnt,id=3)
def do_something(sc): print "Doing stuff..." global previous_run global previous_wicket # do your stuff c = Cricbuzz() matches = c.matches() for match in matches: print match if(match['srs'] == 'Indian Premier League, 2018'): # print match score = c.livescore(match['id'])['batting']['score'] print score print c.commentary(match['id']) runs = int(score[0]['runs']) wicket = int(score[0]['wickets']) overs = (score[0]['overs']) print "---------------------" break diff_wicket = wicket - previous_wicket print "Diff wicket" + str(diff_wicket) if(diff_wicket>0): print "OUTTTTTTT" timer_video("Out", overs) diff_runs = runs - previous_run print "Diff Runs " + str(diff_runs) if(diff_runs>=4): print 4 timer_video("Boundry",overs) ## do something elif(diff_runs==3): print 3 ## do another thing elif(diff_runs==2): print 2 ## do third thing elif(diff_runs==1): print 1 previous_run = runs previous_wicket = wicket s.enter(2, 1, do_something, (sc,))
def get(self, mid): c = Cricbuzz() dict_1 = {} list_1 = [] commentary_recent = c.commentary(mid) # print commentary_recent comment_1 = commentary_recent['commentary'] for comm in comment_1: over = comm['over'] if over is not None: try: dict_1['over'] = over print over commentaryyy = comm['comm'] details = commentaryyy.split(',')[0] print("bowler/batsman", details) dict_1['details'] = details runs = re.sub("<.*?>", "", commentaryyy.split(',')[1]) runs = runs.split(' ')[1] if (runs == 'FOUR'): runs = 4 elif (runs == 'no'): runs = 0 elif (runs == 'wide'): runs = 1 elif (runs == 'leg'): runs = 1 elif (runs == 'SIX'): runs = 6 elif (over is None): runs = 0 print(runs) dict_1['runs'] = runs commentaryyy = re.sub("<.*?>", "", commentaryyy) print("Commentary", commentaryyy) dict_1['commentary'] = commentaryyy list_1.append(dict_1) dict_1 = {} except: pass print list_1 return list_1[0], 200
def commentary(mid): """ To Fetch commentary of the match""" c = Cricbuzz() matches = c.matches() for match in matches: if match['id'] == mid: commentary = c.commentary(match['id'])['commentary'] print("\n--COMMENTARY--\n") for index in commentary: print(colors(index, 32)) print("\n")
def index(): c = Cricbuzz() match = c.matches() mid = (match[0]['id']) livescore = c.livescore(mid=mid) scorecard = c.scorecard(mid=mid) matchinfo = c.matchinfo(mid=mid) commentary = c.commentary(mid=mid) result = {"matches": match, "livescore": livescore, "scorecard": scorecard, "matchinfo": matchinfo, "commentary": commentary} final = jsonify(result) return f"{final}"
def cricCommentry(): c = Cricbuzz() matches = c.matches() # for match in matches: match=matches[0] # print( match) # if(match['mchstate'] != 'nextlive'): # print (c.livescore(match['id'])) # print( c.commentary(match['id'])) # print( c.scorecard(match['id'])) print('sun',c.commentary(match['id'])['commentary'][0]['comm']) a,b=c.commentary(match['id'])['commentary'][0]['comm'],'' while(1): if(a!=b): # speak(a) d=c.scorecard(match['id'])['scorecard'] speak(a) speak(d[0]['batteam']+'score is '+d[0]['runs']+'for'+d[0]['wickets']+'wickets') b=a else: a=c.commentary(match['id'])['commentary'][0]['comm']
def get_cricket_response(self, message: Dict[str, str], bot_handler: Any) -> str: content = message['content'] words = content.lower().split() c = Cricbuzz() matches = c.matches() val = "\n" + match + "\n" for match in matches: if (match['mchstate'] != 'nextlive'): val = val + c.livescore(match['id']) + "\n" val = val + c.commentary(match['id']) + "\n" val = val + c.scorecard(match['id']) + "\n" return val
def Scorecard(request, id): Z = Cricbuzz() m = Z.scorecard(str(id)) comm = Z.commentary(str(id)) if m['matchinfo']['mchstate'] == "Result": return test(request, m, comm) elif (m['matchinfo']['mchstate'] == "inprogress") or (m['matchinfo']['mchstate'] == "innings break"): if len(m['scorecard']) == 2: return test(request, m, comm) elif len(m['scorecard']) == 1: return test1(request, m, comm) return len(m)
def getSixer(match_id): import time time.sleep(10) from pycricbuzz import Cricbuzz import re from interruptingcow import timeout c= Cricbuzz() data = c.commentary(match_id) commentary_live = data['commentary'][0]['comm'] four = 'SIX' x = bool(re.findall(four,commentary_live)) if x is True: print('Sixer!!') sendEmail()
def commentary(mid): print(mid) c = Cricbuzz() comm = c.commentary(mid) comstring = comm["commentary"] #print(comm) #co = json.loads(comm) #co = json.dumps(comm, indent=4, sort_keys=True) a = "" for i in comstring: a = a + i["comm"] b = remove_html_tags(a) if len(b) == 0: print(type(b)) return (b)
def refresh(): c = Cricbuzz() match = c.matches() mid = match[1]['id'] matches = match[1] livescore = c.livescore(mid=mid) scorecard = c.scorecard(mid=mid) matchinfo = c.matchinfo(mid=mid) commentary = c.commentary(mid=mid) result = {} result['matches'] = matches result['livescore'] = livescore result['scorecard'] = scorecard result['matchinfo'] = matchinfo result['commentary'] = commentary return result
def cricket(): c = Cricbuzz() match = c.matches() mid = (match[0]['id']) livescore = c.livescore(mid=mid) scorecard = c.scorecard(mid=mid) matchinfo = c.matchinfo(mid=mid) commentary = c.commentary(mid=mid) result = [{ "matches": match, "livescore": livescore, "scorecard": scorecard, "matchinfo": matchinfo, "commentary": commentary }] return result
def buzz(): c = Cricbuzz() matches = c.matches() h = c.livescore(['4']) print(h) result = [] l = [] l.append(h['matchinfo']['status']) l.append(h['batting']['team']) l.append(h['batting']['score'][0]['overs'] + "overs") l.append(h['batting']['score'][0]['runs'] + "/" + h['batting']['score'][0]['wickets']) #l.append(h['bowling']['team']) #l.append(h['bowling']['score'][0]['overs']+"overs") #l.append(h['bowling']['score'][0]['runs']+"/"+h['bowling']['score'][0]['wickets']) summary = " ".join(l) batting = [] for i in range(len(h['batting']['batsman'])): batting.append(h['batting']['batsman'][i]['name']) batting.append(h['batting']['batsman'][i]['runs'] + "(" + h['batting']['batsman'][i]['balls'] + ")") m = " ".join(batting) bowling = [] for i in range((len(h['bowling']['bowler']))): bowling.append(h['bowling']['bowler'][i]['name']) bowling.append(h['bowling']['bowler'][i]['overs'] + "overs") bowling.append(h['bowling']['bowler'][i]['runs'] + "runs") bowling.append(h['bowling']['bowler'][i]['wickets'] + "wickets") bow = " ".join(bowling) com_list = [] com = c.commentary(['1']) for i in range(2): com_list.append(com['commentary'][i]) result.append(summary) result.append(m) result.append(bow) result.append("\n".join(com_list)) return (result)
class Cricket(): """ Enter cricket and follow the instructions """ def __init__(self): self.c = Cricbuzz() def __call__(self, jarvis, s): self._refresh(jarvis) self.score(jarvis) def _refresh(self, jarvis): spinner = SpinnerThread('Fetching ', 0.15) spinner.start() self.all_match_data = self.c.matches() self.matches = [] d = {} for match in self.all_match_data: d['id'] = match['id'] d['srs'] = match['srs'] d['mnum'] = match['mnum'] self.matches.append(d.copy()) spinner.stop() jarvis.say('DONE fetching match details', Fore.GREEN) def live_score(self, index): if self.all_match_data[index]['mchstate'] == 'preview': return(Fore.RED + "MATCH YET TO BEGIN") selected_match = self.all_match_data[index] data = self.c.livescore(self.matches[index]['id']) score = {} score['matchinfo'] = "{}, {}".format( selected_match['srs'], selected_match['mnum']) score['status'] = "{}".format(selected_match['status']) score['bowling'] = data['bowling'] score['batting'] = data['batting'] text = '' text += Fore.LIGHTYELLOW_EX + \ score['matchinfo'] + '\n' + score['status'] + '\n\n' text += Fore.BLUE + score['batting']['team'] + Fore.BLACK for scr in reversed(score['batting']['score']): text += " :- {}/{} in {} overs\n".format( scr['runs'], scr['wickets'], scr['overs']) for b in reversed(score['batting']['batsman']): text += "{} : {}({}) \n".format( b['name'].strip('*'), b['runs'], b['balls']) text += Fore.BLUE + '\n' + score['bowling']['team'] + Fore.BLACK for scr in reversed(score['bowling']['score']): text += " :- {}/{} in {} overs\n".format( scr['runs'], scr['wickets'], scr['overs']) for b in reversed(score['bowling']['bowler']): text += "{} : {}/{} \n".format(b['name'].strip('*'), b['wickets'], b['runs']) text += Fore.RESET return text def commentary(self, index): selected_match = self.all_match_data[index] data = self.c.commentary(self.matches[index]['id']) comm = {} comm['matchinfo'] = "{}, {}".format( selected_match['srs'], selected_match['mnum']) comm['status'] = "{}".format(selected_match['status']) comm['commentary'] = data['commentary'] text = [] for com in comm['commentary']: line = '' if com['over']: line += com['over'] + ' : ' line += "{}\n\n".format(com['comm']) # doing bold breaklines and italics looks good in terminal text.append( line.replace( '<b>', '\033[1m').replace( '</b>', '\033[0m') .replace( '<br/>', '\n').replace( '<i>', '\x1B[3m').replace( '</i>', '\x1B[23m')) text.reverse() commentary = Fore.LIGHTYELLOW_EX + \ comm['matchinfo'] + '\n' + comm['status'] + '\n\n' + Fore.RESET for line in text: commentary += line return commentary def scorecard(self, index): selected_match = self.all_match_data[index] data = self.c.scorecard(self.matches[index]['id']) card = {} card['matchinfo'] = "{}, {}".format( selected_match['srs'], selected_match['mnum']) card['status'] = "{}".format(selected_match['status']) card['scorecard'] = data['scorecard'] text = '' text += Fore.LIGHTYELLOW_EX + \ card['matchinfo'] + '\n' + card['status'] + '\n\n' text += Fore.BLACK + '*' * 35 + '\n\n' for scr in reversed(card['scorecard']): text += Fore.LIGHTYELLOW_EX + "{}\nInnings: {}\n{}/{} in {} overs\n\n".format( scr['batteam'], scr['inng_num'], scr['runs'], scr['wickets'], scr['overs']) text += Fore.BLUE + "Batting\n" text += Fore.RED + \ "{:<17} {:<3} {:<3} {:<3} {}\n\n".format('Name', 'R', 'B', '4', '6') for b in scr['batcard']: text += Fore.BLACK + "{:<17} {:<3} {:<3} {:<3} {}\n{}\n\n".format( b['name'], b['runs'], b['balls'], b['fours'], b['six'], b['dismissal']) text += Fore.LIGHTYELLOW_EX + "-" * 35 + "\n\n" text += Fore.BLUE + "Bowling\n" text += Fore.RED + \ "{:<17} {:<5} {:<3} {:<3} {}\n\n".format('Name', 'O', 'M', 'R', 'W') for b in scr['bowlcard']: text += Fore.BLACK + "{:<17} {:<5} {:<3} {:<3} {}\n\n".format( b['name'], b['overs'], b['maidens'], b['runs'], b['wickets']) text += Fore.BLUE + '*' * 35 + '\n\n' return text def score(self, jarvis): print(Fore.RED + "\nALL MATCHES\n" + Fore.LIGHTBLUE_EX) if self.matches == []: print("No Matches Being Played!\n", Fore.RED) return for i, m in enumerate(self.matches, 1): print("{}. {} {}".format(str(i), m['srs'], m['mnum'])) while True: try: choice = int(jarvis.input('\nEnter choice (number): ', Fore.RED)) while choice < 1 or choice > len(self.matches): print(Fore.BLACK + '\nWrong choice') choice = int(jarvis.input('\nEnter choice again: ', Fore.RED)) break except ValueError: print("Invalid type of choice. Please enter an integer number") selected_match_id = choice - 1 print('') res = self.live_score(selected_match_id) print(res) if(res == Fore.RED + "MATCH YET TO BEGIN"): return while True: print(Fore.LIGHTBLUE_EX + '1. Full Score Card') print('2. Commentary') print('3. Refresh Score') print('4. Quit' + Fore.RESET) while True: try: choice = int(jarvis.input('\nEnter choice (number): ', Fore.RED)) while choice < 1 or choice > 4: print(Fore.BLACK + '\nWrong choice') choice = int(jarvis.input('\nEnter choice again: ', Fore.RED)) break except ValueError: print("Invalid type of choice. Please enter an integer number") print('') if choice == 1: print(self.scorecard(selected_match_id)) ref = jarvis.input('Do you want to refresh:(y/n) ', Fore.RED) while ref == 'y': print(self.scorecard(selected_match_id)) ref = jarvis.input('Do you want to refresh:(y/n) ', Fore.RED) elif choice == 2: print(self.commentary(selected_match_id)) ref = jarvis.input('Do you want to refresh:(y/n) ', Fore.RED) while ref == 'y': print(self.commentary(selected_match_id)) ref = jarvis.input('Do you want to refresh:(y/n) ', Fore.RED) elif choice == 3: ref = 'y' while ref == 'y': print(self.live_score(selected_match_id)) ref = jarvis.input('Do you want to refresh:(y/n) ', Fore.RED) else: return
def commentary(mid): c = Cricbuzz() comm = c.commentary(mid) comms = list(comm.values())[0] latest_comm = comms[0] return str(latest_comm)
class Scraper: def __init__(self): self.cricbuzz = Cricbuzz() self.current_over = "-1" self.logger_instance = Logger("app.log") def _get_matches(self): return self.cricbuzz.matches() @staticmethod def _get_criteria(): return { 'type': "T20", 'mchstate': "inprogress", 'srs': "Indian Premier League 2019" } @staticmethod def _check_if_valid_match(match, criteria): bools = [match[key] == value for key, value in criteria.items()] return all(bools) def _get_current_match_id(self, matches, criteria): for match in matches: current_ipl_match = self._check_if_valid_match(match, criteria) if current_ipl_match is True: return match['id'] return None def _get_commentary(self, match_id): return self.cricbuzz.commentary(match_id)['commentary'] @staticmethod def _comm_after_new_innings(comms): split_index = len(comms) if len(comms) == 0: return comms for index, comm in enumerate(comms): if "will open the attack" in comm['comm']: split_index = index return comms[:split_index] def _new_six_scored(self, commentary, given_last_ball=None): last_ball_commentary = [ comm for comm in commentary if 'over' in comm and comm['over'] is not None ] new_innings_comm = self._comm_after_new_innings(commentary) last_30_sixes = [ comm for comm in new_innings_comm if "<b>SIX</b>" in comm['comm'] ] if len(last_ball_commentary) == 0: last_ball = '0.0' else: last_ball = last_ball_commentary[0]['over'] if len(last_30_sixes) > 0 and float( last_30_sixes[0]['over']) > float(given_last_ball): return {"status": True, "last_ball": last_ball} return {"status": False, "last_ball": last_ball} def scrape(self): self.logger_instance.info("Querying Matches...") matches = self._get_matches() match_id = self._get_current_match_id(matches, self._get_criteria()) if match_id is not None: self.logger_instance.info("Match is found with ID: %s" % match_id) data = self._new_six_scored(self._get_commentary(match_id), self.current_over) if data['last_ball'] == "19.6": self.current_over = "-1" else: self.current_over = data['last_ball'] if data['status'] is True: self.logger_instance.info("A new six was scored at ball: %s" % data["last_ball"]) return {"status": True, "data": data} self.logger_instance.warning("No match with given criteria found.") return {"status": False, "data": {}}
from pycricbuzz import Cricbuzz c = Cricbuzz() matches = c.matches() for match in matches: print(match) if(match['mchstate'] != 'nextlive'): print(c.livescore(match['id'])) print(c.commentary(match['id'])) print(c.scorecard(match['id']))
b['runs'], s(11-len(b['runs'])), \ b['overs'], s(10-len(b['overs'])), \ b['wickets'], s(11-len(b['wickets'])), \ b['maidens'])) print_line(53) def print_com(com): if not com: return print('\n') comm = com.get('commentary', [{'comm': 'No comments', 'over': u''}])[0] print((comm['over'] if comm['over'] else '') + ' : ' + comm['comm']) if __name__ == '__main__': match_id = sys.argv[1] c = Cricbuzz() sc = c.livescore(match_id) com = c.commentary(match_id) ba = sc.get('batting', None) bo = sc.get('bowling', None) print_teamscore(sc) print_batting_score(ba) print_bowling_score(bo) print_com(com)
from pycricbuzz import Cricbuzz c = Cricbuzz() commentary1 = [] current_game3 = {} matches = c.matches() for match in matches: if match['mchstate'] != 'nextlive': col= (c.commentary(match['id'])) for my_str in col['commentary']: current_game3["commentary2"] = my_str for comment in commentary1: a = comment['commentary2'].replace('<br/>', '\n') commentary1.append(a) current_game3 = {} print(commentary1)
from tkinter import * from pycricbuzz import Cricbuzz root = Tk() root.title("live cricket score") root.geometry("800x800") c = Cricbuzz() match = c.matches() score = c.livescore(match[0]['id']) commentary = c.commentary(match[0]['id']) score_board = c.scorecard(match[0]['id']) for a in score: print(a) for b in score[a]: print(b, ':', score[a][b]) s = str(score_board) k = s.replace(",", "\n") score1 = Label(root, font=("time", 15, "bold"), bg="white", text=k) score1.grid(row=2, column=2, pady=25, padx=100) print(commentary) root.mainloop()
class Cricket(): """ Enter cricket and follow the instructions """ def __init__(self): self.c = Cricbuzz() def __call__(self, jarvis, s): self._refresh() self.score(jarvis) def _refresh(self): self.all_match_data = self.c.matches() self.matches = [] d = {} for match in self.all_match_data: d['id'] = match['id'] d['srs'] = match['srs'] d['mnum'] = match['mnum'] self.matches.append(d.copy()) def live_score(self, index): if self.all_match_data[index]['mchstate'] == 'preview': return (Fore.RED + "MATCH YET TO BEGIN") selected_match = self.all_match_data[index] data = self.c.livescore(self.matches[index]['id']) score = {} score['matchinfo'] = "{}, {}".format(selected_match['srs'], selected_match['mnum']) score['status'] = "{}".format(selected_match['status']) score['bowling'] = data['bowling'] score['batting'] = data['batting'] text = '' text += Fore.LIGHTYELLOW_EX + score['matchinfo'] + '\n' + score[ 'status'] + '\n\n' text += Fore.BLUE + score['batting']['team'] + Fore.BLACK for scr in reversed(score['batting']['score']): text += " :- {}/{} in {} overs\n".format(scr['runs'], scr['wickets'], scr['overs']) for b in reversed(score['batting']['batsman']): text += "{} : {}({}) \n".format(b['name'].strip('*'), b['runs'], b['balls']) text += Fore.BLUE + '\n' + score['bowling']['team'] + Fore.BLACK for scr in reversed(score['bowling']['score']): text += " :- {}/{} in {} overs\n".format(scr['runs'], scr['wickets'], scr['overs']) for b in reversed(score['bowling']['bowler']): text += "{} : {}/{} \n".format(b['name'].strip('*'), b['wickets'], b['runs']) text += Fore.RESET return text def commentary(self, index): selected_match = self.all_match_data[index] data = self.c.commentary(self.matches[index]['id']) comm = {} comm['matchinfo'] = "{}, {}".format(selected_match['srs'], selected_match['mnum']) comm['status'] = "{}".format(selected_match['status']) comm['commentary'] = data['commentary'] text = [] for com in comm['commentary']: line = '' if com['over']: line += com['over'] + ' : ' line += "{}\n\n".format(com['comm']) # doing bold breaklines and italics looks good in terminal text.append( line.replace('<b>', '\033[1m').replace( '</b>', '\033[0m').replace('<br/>', '\n').replace( '<i>', '\x1B[3m').replace('</i>', '\x1B[23m')) text.reverse() commentary = Fore.LIGHTYELLOW_EX + comm['matchinfo'] + '\n' + comm[ 'status'] + '\n\n' + Fore.RESET for line in text: commentary += line return commentary def scorecard(self, index): selected_match = self.all_match_data[index] data = self.c.scorecard(self.matches[index]['id']) card = {} card['matchinfo'] = "{}, {}".format(selected_match['srs'], selected_match['mnum']) card['status'] = "{}".format(selected_match['status']) card['scorecard'] = data['scorecard'] text = '' text += Fore.LIGHTYELLOW_EX + card['matchinfo'] + '\n' + card[ 'status'] + '\n\n' text += Fore.BLACK + '*' * 35 + '\n\n' for scr in reversed(card['scorecard']): text += Fore.LIGHTYELLOW_EX + "{}\nInnings: {}\n{}/{} in {} overs\n\n".format( scr['batteam'], scr['inng_num'], scr['runs'], scr['wickets'], scr['overs']) text += Fore.BLUE + "Batting\n" text += Fore.RED + "{:<17} {:<3} {:<3} {:<3} {}\n\n".format( 'Name', 'R', 'B', '4', '6') for b in scr['batcard']: text += Fore.BLACK + "{:<17} {:<3} {:<3} {:<3} {}\n{}\n\n".format( b['name'], b['runs'], b['balls'], b['fours'], b['six'], b['dismissal']) text += Fore.LIGHTYELLOW_EX + "-" * 35 + "\n\n" text += Fore.BLUE + "Bowling\n" text += Fore.RED + "{:<17} {:<5} {:<3} {:<3} {}\n\n".format( 'Name', 'O', 'M', 'R', 'W') for b in scr['bowlcard']: text += Fore.BLACK + "{:<17} {:<5} {:<3} {:<3} {}\n\n".format( b['name'], b['overs'], b['maidens'], b['runs'], b['wickets']) text += Fore.BLUE + '*' * 35 + '\n\n' return text def score(self, jarvis): print(Fore.RED + "\nALL MATCHES\n" + Fore.LIGHTBLUE_EX) if self.matches == []: print("No Matches Being Played!\n", Fore.RED) return for i, m in enumerate(self.matches, 1): print("{}. {} {}".format(str(i), m['srs'], m['mnum'])) while 1: try: choice = int( input(Fore.RED + '\nEnter choice (number): ' + Fore.RESET)) while choice < 1 or choice > len(self.matches): print(Fore.BLACK + '\nWrong choice') choice = int( input(Fore.RED + '\nEnter choice again: ' + Fore.RESET)) break except ValueError: print("Invalid type of choice. Please enter an integer number") selected_match_id = choice - 1 print('') res = self.live_score(selected_match_id) print(res) if (res == Fore.RED + "MATCH YET TO BEGIN"): return while True: print(Fore.LIGHTBLUE_EX + '1. Full Score Card') print('2. Commentary') print('3. Refresh Score') print('4. Quit' + Fore.RESET) while 1: try: choice = int( input(Fore.RED + '\nEnter choice (number): ' + Fore.RESET)) while choice < 1 or choice > 4: print(Fore.BLACK + '\nWrong choice') choice = int( input(Fore.RED + '\nEnter choice again: ' + Fore.RESET)) break except ValueError: print( "Invalid type of choice. Please enter an integer number" ) print('') if choice == 1: print(self.scorecard(selected_match_id)) ref = input(Fore.RED + 'Do you want to refresh:(y/n) ' + Fore.RESET) while ref == 'y': print(self.scorecard(selected_match_id)) ref = input(Fore.RED + 'Do you want to refresh:(y/n) ' + Fore.RESET) elif choice == 2: print(self.commentary(selected_match_id)) ref = input(Fore.RED + 'Do you want to refresh:(y/n) ' + Fore.RESET) while ref == 'y': print(self.commentary(selected_match_id)) ref = input(Fore.RED + 'Do you want to refresh:(y/n) ' + Fore.RESET) elif choice == 3: ref = 'y' while ref == 'y': print(self.live_score(selected_match_id)) ref = input(Fore.RED + 'Do you want to refresh:(y/n) ' + Fore.RESET) else: return
class Cricket: def __init__(self): self.cb = Cricbuzz() self.all_matches = self.cb.matches() self.run = True def live_matches(self): msg = "* 🏏 All live matches *\n\n" for match in self.all_matches: if match['mchstate'] == 'inprogress': msg += match["team1"]["name"]+" v/s " + match["team2"]["name"]+ "," \ + match["srs"] + " - " + match["mnum"] + "\n\n" else: msg += "No live matches" return msg def commentary(self, match_id): commentary = self.cb.commentary(match_id) msg = f"Live commentary - {match_id}\n\n" for com in commentary["commentary"]: msg += com['comm'].replace("<b>","").replace("</b>","").replace("<br/>","\n") + "\n" return msg def score_card(self, match_id): match = self.cb.matchinfo(match_id) score = self.cb.scorecard(match_id) msg = f"<code>{match['team1']['name']} v/s {match['team2']['name']}-Scorecard</code>\n" for scr in reversed(score["scorecard"]): batcard = "".join([f"Name: {batcard['name']}\n Runs: {batcard['runs']}\n Balls: {batcard['balls']}\n Fours: {batcard['fours']}\n Six: {batcard['six']}\n Dismissal: {batcard['dismissal']}\n" for batcard in scr['batcard']]) bowlcard = "".join([f"Name: {bowlcard['name']}\n Overs: {bowlcard['overs']}\n Maidens: {bowlcard['maidens']}\n Runs: {bowlcard['runs']}\n Six: {bowlcard['wickets']}\n Wides: {bowlcard['wides']}\n No Balls: {bowlcard['nballs']}\n" for bowlcard in scr['bowlcard']]) msg += f"INN: {scr['inng_num']}\n" \ f" Batteam: {scr['batteam']}\n" \ f" {scr['runs']}/{scr['wickets']} in {scr['overs']} overs\n" \ f" Bowlteam: {scr['bowlteam']}\n" \ "\n\n" return msg def players(self, match_id): match = self.cb.matchinfo(match_id) msg = f'Team 1: {match["team1"]["name"]}\n' msg += "Squad:\n " + " ".join([squad + "\n" for squad in match["team1"]["squad"]]) msg += f'\n\nTeam 2: {match["team2"]["name"]}\n' msg += "Squad:\n " + " ".join([squad + "\n" for squad in match["team2"]["squad"]]) return msg def match_info(self, match_id): match = self.cb.matchinfo(match_id) msg = "*Series:* _" + match["srs"] + "_\n" \ "*Match No:* _" + match["mnum"] + "_\n" \ "*Type:* _" + match["type"] + "_\n" \ "*State:* _" + match["mchstate"] + "_\n" \ "*Status:* _" + match["status"] +"_\n" \ "*Venue:* _" + match["venue_name"] + " " + match["venue_location"] + "_\n" \ "*Toss:* _" + match["toss"] + "_\n" \ "*Team 1:* _" + match["team1"]["name"] + "_\n" \ "*Team 2:* _" + match["team2"]["name"] + "_\n" \ f"*Officials:*\n _umpire 1: {match['official']['umpire1']['name']}\n umpire 2: {match['official']['umpire2']['name']}\n umpire 3: {match['official']['umpire3']['name']}\n referee: {match['official']['referee']['name']}_\n" \ "*Start Time:* _" + match["start_time"] + "_\n" \ "*Team 1:* _" + match["team1"]["name"] + "_\n" \ "*Team 2:* _" + match["team2"]["name"] + "_\n" return msg def live_score(self, message, match_id): then = time.time() while self.run: elapsed = time.time() - then if elapsed > 10800: message.delete() break match_info = self.cb.matchinfo(match_id) live_score = self.cb.livescore(match_id) last_updated = datetime.utcnow() + timedelta(minutes=30, hours=5) batting, bowling = live_score["batting"], live_score["bowling"] msg = '' msg += match_info['srs'] + '\n' + match_info['status'] + '\n\n' msg += batting['team'] + "\n" for score in batting['score']: msg += f" INN: {score['inning_num']} {score['runs']}/{score['wickets']} in {score['overs']} overs\n" for bts in batting['batsman']: msg += f" {bts['name']} : {bts['runs']}({bts['balls']}) \n" msg += bowling['team'] + "\n" for score in bowling['score']: msg += f" INN: {score['inning_num']} {score['runs']}/{score['wickets']} in {score['overs']} overs\n" for balls in bowling['bowler']: msg += f" {balls['name'].strip('*')} : {balls['wickets']}/{balls['runs']} \n" msg += f"\n_Last updated: {last_updated.strftime('%I:%M:%S %P')} [IST]_" try: message.edit_text( text = msg, parse_mode="markdown", reply_markup = InlineKeyboardMarkup([ [ InlineKeyboardButton(text=f"Stop",callback_data=f"stop"), InlineKeyboardButton(text=f"Force Refresh",callback_data=f"force_ref-{match_id}") ] ]) ) except: pass time.sleep(60) else: self.run = True message.edit_text("Terminating...") time.sleep(2) message.delete() def list_matches_buttons(self, cb_data): btns = [] for match in self.all_matches: btns.append([InlineKeyboardButton(text=f" {match['team1']['name']} v/s {match['team2']['name']} ",callback_data=f"{cb_data}-{match['id']}")]) btns.append([ InlineKeyboardButton(text=f"<<< Go back to home",callback_data=f"back_to_home")]) return btns
from pycricbuzz import Cricbuzz c = Cricbuzz() print(c.matches()) print(c.commentary('30430')) print(c.scorecard['30430'])
# before executing the code install the "pycricbuzz" package # use "pip install pycricbuzz" or "pip3 install pycricbuzz" from pycricbuzz import Cricbuzz import json c = Cricbuzz() # create a cricbuzz object matches = c.matches() for match in matches: print(match) print(c.livescore(match['id'])) # fetches the lievscore print(c.commentary(match['id'])) # fetch the commentary of the match print(c.scorecard(match['id'])) # fetch the scorecard of the match
class Cricket(Plugin): """ Enter cricket and follow the instructions """ def __init__(self): self.c = Cricbuzz() def require(self): yield ('network', True) def complete(self): pass def alias(self): pass def run(self, jarvis, s): self.score(jarvis) def match_id(self, desc): all_matches = self.c.matches() for match in all_matches: if match['mchdesc'].title() == desc: return match['id'] else: return None def all_matches(self): match_data = self.c.matches() matches = [] for match in match_data: matches.append(match['mchdesc']) return matches def live_score(self, desc): mid = self.match_id(desc) res = self.c.matches() for value in res: if value['id'] == mid: if value['mchstate'] == 'preview': text = Fore.RED + "MATCH YET TO BEGIN" return text data = self.c.livescore(mid) score = {} score['matchinfo'] = "{}, {}".format(data['matchinfo']['mnum'], data['matchinfo']['mchdesc']) score['status'] = "{}, {}".format( data['matchinfo']['mchstate'].title(), data['matchinfo']['status']) score['bowling'] = data['bowling'] score['batting'] = data['batting'] text = '' text += Fore.LIGHTYELLOW_EX + score['matchinfo'] + '\n' + score[ 'status'] + '\n\n' text += Fore.BLUE + score['batting']['team'] + '\n' + Fore.BLACK for scr in reversed(score['batting']['score']): text += "{} :- {}/{} in {} overs\n".format(scr['desc'], scr['runs'], scr['wickets'], scr['overs']) for b in reversed(score['batting']['batsman']): text += "{} : {}({}) \n".format(b['name'].strip('*'), b['runs'], b['balls']) text += Fore.BLUE + "\n" + score['bowling']['team'] + '\n' + Fore.BLACK for scr in reversed(score['bowling']['score']): text += "{} :- {}/{} in {} overs\n".format(scr['desc'], scr['runs'], scr['wickets'], scr['overs']) for b in reversed(score['bowling']['bowler']): text += "{} : {}/{} \n".format(b['name'].strip('*'), b['wickets'], b['runs']) text += Fore.RESET return text def commentary(self, desc): mid = self.match_id(desc) data = self.c.commentary(mid) comm = {} comm['matchinfo'] = "{}, {}".format(data['matchinfo']['mnum'], data['matchinfo']['mchdesc']) comm['status'] = "{}, {}".format(data['matchinfo']['mchstate'].title(), data['matchinfo']['status']) comm['commentary'] = data['commentary'] text = '' text += Fore.LIGHTYELLOW_EX + comm['matchinfo'] + '\n' + comm[ 'status'] + '\n\n' + Fore.RESET for com in comm['commentary']: text += "{}\n\n".format(com) return text def scorecard(self, desc): mid = self.match_id(desc) data = self.c.scorecard(mid) card = {} card['matchinfo'] = "{}, {}".format(data['matchinfo']['mnum'], data['matchinfo']['mchdesc']) card['status'] = "{}, {}".format(data['matchinfo']['mchstate'].title(), data['matchinfo']['status']) card['scorecard'] = data['scorecard'] text = '' text += Fore.LIGHTYELLOW_EX + card['matchinfo'] + '\n' + card[ 'status'] + '\n\n' text += Fore.BLACK + '*' * 35 + '\n\n' for scr in reversed(card['scorecard']): text += Fore.LIGHTYELLOW_EX + "{} {}\n{}/{} in {} overs\n\n".format( scr['batteam'], scr['inngdesc'], scr['runs'], scr['wickets'], scr['overs']) text += Fore.BLUE + "Batting\n" text += Fore.RED + "{:<17} {:<3} {:<3} {:<3} {}\n\n".format( 'Name', 'R', 'B', '4', '6') for b in scr['batcard']: text += Fore.BLACK + "{:<17} {:<3} {:<3} {:<3} {}\n{}\n\n".format( b['name'], b['runs'], b['balls'], b['fours'], b['six'], b['dismissal']) text += Fore.LIGHTYELLOW_EX + "-" * 35 + "\n\n" text += Fore.BLUE + "Bowling\n" text += Fore.RED + "{:<17} {:<5} {:<3} {:<3} {}\n\n".format( 'Name', 'O', 'M', 'R', 'W') for b in scr['bowlcard']: text += Fore.BLACK + "{:<17} {:<5} {:<3} {:<3} {}\n\n".format( b['name'], b['overs'], b['maidens'], b['runs'], b['wickets']) text += Fore.BLUE + '*' * 35 + '\n\n' return text def score(self, jarvis): matches = self.all_matches() jarvis.say(Fore.RED + "\nALL MATCHES\n" + Fore.LIGHTBLUE_EX) if matches == []: jarvis.say("No Matches Being Played!\n", Fore.RED) return for i, m in enumerate(matches, 1): jarvis.say("{}. {}".format(str(i), m)) choice = int(input(Fore.RED + '\nEnter choice (number): ' + Fore.RESET)) while choice < 1 or choice > len(matches): jarvis.say(Fore.BLACK + '\nWrong choice') choice = int( input(Fore.RED + '\nEnter choice again: ' + Fore.RESET)) desc = matches[choice - 1].title() jarvis.say('') res = self.live_score(desc) jarvis.say(res) jarvis.say("\n") if (res == Fore.RED + "MATCH YET TO BEGIN"): return jarvis.say(self.live_score(desc)) jarvis.say(Fore.LIGHTBLUE_EX + '1. Full Score Card') jarvis.say('2. Commentary') jarvis.say('3. Refresh Score') jarvis.say('4. Quit' + Fore.RESET) choice = int(input(Fore.RED + '\nEnter choice (number): ' + Fore.RESET)) while choice < 1 or choice > 4: jarvis.say(Fore.BLACK + '\nWrong choice') choice = int( input(Fore.RED + '\nEnter choice again: ' + Fore.RESET)) jarvis.say('') if choice == 1: ref = 'y' while ref == 'y': jarvis.say(self.scorecard(desc)) ref = input(Fore.RED + 'Do you want to refresh:(y/n) ' + Fore.RESET) jarvis.say('\n') elif choice == 2: ref = 'y' while ref == 'y': jarvis.say(self.commentary(desc)) ref = input(Fore.RED + 'Do you want to refresh:(y/n) ' + Fore.RESET) jarvis.say('\n') elif choice == 3: ref = 'y' while ref == 'y': jarvis.say(self.live_score(desc)) ref = input(Fore.RED + 'Do you want to refresh:(y/n) ' + Fore.RESET) jarvis.say('\n')
from pycricbuzz import Cricbuzz c = Cricbuzz() matches = c.matches() match = matches[0] # print c.livescore(match['id']) commentary_recent = c.commentary(match['id']) # print commentary_recent comment_1 = commentary_recent['commentary'] for comm in comment_1: try: over = comm['over'] print over commentaryyy = comm['comm'] details = commentaryyy.split(',')[0] print("bowler/batsman", details) runs = commentaryyy.split(',')[1] print("RUNS", runs) print("Commentary", commentaryyy) except: pass
def commentary(mid): c = Cricbuzz() comm = c.commentary(mid) return(comm)
#pip install pycricbuzz from pycricbuzz import Cricbuzz a = Cricbuzz() match = a.matches() for x in match: print(x) if (x['mchstate'] != 'nextlive'): print(a.livescore(x['id'])) print(a.commentary(x['id'])) print(a.scorecard(x['id']))