Esempio n. 1
0
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)
Esempio n. 2
0
def match_id():
    c = Cricbuzz()
    matches = c.matches()
    for I in matches:
        if I['srs'] == 'Indian Premier League 2020' and (
                I['mchstate'] == 'toss' or I['mchstate'] == 'inprogress'):
            return I['id']
Esempio n. 3
0
def fun():
	#we enter our Twilio accoundSid and authToken
	accountSid 		= "SKf3e6cefcec4f940c1d64c160d88c4770"
	authToken  		= "09jT4lchanP7hKoUqc5xLX8ZDy4mxDfE"
	# connecting to TWILIO API
	twilioClient	= Client(accountSid, authToken)
	myTwilioNumber 	= ""
	destCellPhone 	= ""
	#url = "http://synd.cricbuzz.com/j2me/1.0/livematches.xml"
	#to extract the matches 
	cric       		= Cricbuzz()
	details			= cric.matches()
 
	#To filter out the None objects from details
	details=filter(None, details)
	message="No match in progress"
 
	for i in details:
		# traversing i
		if 'mchstate' in i:
			if i['mchstate']== 'inprogress':
				id= i['id']
				main=cric.livescore(id)
				ms =main['batting']['score'][0]
				bat1=main['batting']['batsman'][0]
				bat2=main['batting']['batsman'][1]
				#print(bat1['name'])
				message=i['srs']+ "      "+"Format: "+i['type'] +  "\n" + "Score: " +main['batting']['team']+" "+ms['runs'] +'/'+ms['wickets'] +" ("+ms['overs']+")"+"\n" +bat1['name']+":"+bat1['runs']+"("+bat1['balls']+")   "+ bat2['name']+":"+bat1['runs']+"("+bat2['balls']+")"
 
	#Generates the message
	notify2.init("Live Score")
	# shows notification on out desktop
	notify2.Notification("Match currently in progress:",message).show()
Esempio n. 4
0
def fun():
    # url = "http://synd.cricbuzz.com/j2me/1.0/livematches.xml"
    # to extract the matches
    cric = Cricbuzz()
    details = cric.matches()
    # print(details)
    # To filter out the None objects from details
    details = filter(None, details)
    message = "No match in progress"
    for i in details:
        # traversing i
        if 'mchstate' in i:
            print('Series ==>' + i['srs'])  # List All Current Series
            # print('mchstate ==>' + i['mchstate'])  # List All Current Series
            if i['mchstate'] in ['inprogress','stump','rain'] and i['srs'] == 'Ranji Trophy 2019-20':
            # if i['mchstate'] == 'innings break':
            # if i['mchstate'] in ('inprogress','innings break'):
                id = i['id']
                main = cric.livescore(id)
                ms = main['batting']['score'][0]
                bat1 = main['batting']['batsman'][0]
                bat2 = main['batting']['batsman'][1]
                curr_bowler = main['bowling']['bowler'][0]
                # print(bat1['name'])
                # print(curr_bowler['name','overs','runs','wickets'])
                message = "\n" + i['srs'] + "      " + "\n" + "Format: " + i['type'] + "\n" + "Score: " + main['batting'][
                    'team'] + " " + ms['runs'] + '/' + ms['wickets'] + " (" + ms['overs'] + ")" + "\n" + bat1[
                              'name'] + ": " + bat1['runs'] + "(" + bat1['balls'] + ")   " + bat2['name'] + ": " + bat2[
                              'runs'] + "(" + bat2['balls'] + ")" + "\n" + curr_bowler['name'] + ": " + curr_bowler['overs'] + "-" + curr_bowler['runs'] + "-" + curr_bowler['wickets']
    # Generates the message
    print(message)
    return message
Esempio n. 5
0
def cricket_info():
    result = []
    c = Cricbuzz()
    matches = c.matches()
    print(json.dumps(matches, indent=4))
    result.append(matches)
    return jsonify({'matches': result})
Esempio n. 6
0
 def setupUi(self, PyCricket):
     c = Cricbuzz() 
     matches = c.matches()
     livematches=[]
     affected=[]
     for match in matches:
         if(match['mchstate']=='inprogress'):
             livematches.append(match['mchdesc'])
         elif ('rain' in match['mchstate']):
             affected.append(match['mchdesc'])
     
     if len(affected)==0:
         ui.totalaffected=ui.totalaffected+"No Match Affected.."
         
     else:
         for i in range(len(affected)):
             ui.totalaffected=ui.totalaffected+affected[i]+" "
         
     PyCricket.setObjectName("PyCricket")
     PyCricket.resize(544,570)
     
     PyCricket.setMaximumSize(QtCore.QSize(544, 16777215))
     self.raina = QtWidgets.QLabel(PyCricket)
     self.raina.setGeometry(QtCore.QRect(20,550, 501, 16))
     font = QtGui.QFont()
     font.setPointSize(9)
     self.raina.setFont(font)
     self.raina.setObjectName("rainaffected")
     self.raina.setText(ui.totalaffected)
     self.label = QtWidgets.QLabel(PyCricket)
     self.label.setGeometry(QtCore.QRect(80, 30, 121, 20))
     font = QtGui.QFont()
     font.setPointSize(12)
     self.label.setFont(font)
     self.label.setObjectName("label")
     self.livematches = QtWidgets.QComboBox(PyCricket)
     self.livematches.setGeometry(QtCore.QRect(230, 30, 231, 22))
     self.livematches.setObjectName("livematches")
     self.livematches.addItems(livematches)
     self.pushButton = QtWidgets.QPushButton(PyCricket)
     self.pushButton.setGeometry(QtCore.QRect(210, 80,130, 23))
     self.pushButton.setObjectName("pushButton")
     self.pushButton.clicked.connect(self.score)
     self.label_2 = QtWidgets.QLabel(PyCricket)
     self.label_2.setGeometry(QtCore.QRect(20,530, 151, 16))
     font = QtGui.QFont()
     font.setPointSize(10)
     self.label_2.setFont(font)
     self.label_2.setObjectName("label_2")
     self.label_3 = QtWidgets.QLabel(PyCricket)
     self.label_3.setGeometry(QtCore.QRect(80, 130, 401, 301))
     font = QtGui.QFont()
     font.setPointSize(8)
     self.label_3.setFont(font)
     self.label_3.setObjectName("label_3")
     
     
     self.label_3.hide()==True
     self.retranslateUi(PyCricket)
     QtCore.QMetaObject.connectSlotsByName(PyCricket)
Esempio n. 7
0
class LiveScores():
    def __init__(self):
        self.c=Cricbuzz()
        self.all_matches = self.c.matches()
    def gonoobs(self):
        print('---LIVE SCORES---')
        count=0
        for match in reversed(self.all_matches):
            try:
                batting_data=self.c.livescore(match['id'])['batting']
                bowling_data=self.c.livescore(match['id'])['bowling']
                '''
                print(batting_data)
                print(batting_data['team'],':',batting_data['score'][0]['runs'],'/',batting_data['score'][0]['wickets'],'Overs:',batting_data['score'][0]['overs'])
                print('versus ',bowling_data['team'])
                print('status:',self.c.matchinfo(match['id'])['status'])
                count+=1
                #print(self.c.scorecard(match['id']))
                '''
                count+=1
                innings='second' if batting_data['score'][0]['inning_num']=='2' else 'first'
                assistant.say('match '+batting_data['team']+' versus '+bowling_data['team'])
                assistant.say(innings+' innings '+batting_data['team']+' is batting with score '+batting_data['score'][0]['runs']+' at '+batting_data['score'][0]['wickets'])
                gui_obj.widg_obj.BotM('in '+batting_data['score'][0]['overs']+' overs')
                speak('in '+batting_data['score'][0]['overs']+' overs')                

            except:
                pass
        if count==0:
            gui_obj.widg_obj.BotM('NO LIVE MATCHES NOW')
            speak('NO LIVE MATCHES NOW')
Esempio n. 8
0
 def handle_cricket_intent(self, message):
     #self.speak("hello")
     c = Cricbuzz()
     matches = c.matches()
     for match in matches:
         self.speak("match is " + match['mchdesc'])
         self.speak("match status is " + match['status'])
Esempio n. 9
0
def scoreCard(mid):
    """ To Fetch scorecard of a match"""

    c = Cricbuzz()
    matches = c.matches()
    my_data = []
    for match in matches:
        if match['id'] == mid:
            game = c.scorecard(match['id'])
            status = game['matchinfo']['status']
            desc = game['matchinfo']['mchdesc']
            state = game['matchinfo']['mchstate']
            print(colors("\n{} | {} | {}\n".format(desc, status, state), 33))
            try:
                for i in range(2):
                    wickets = game['scorecard'][i]['wickets']
                    runs = game['scorecard'][i]['runs']
                    bowlteam = game['scorecard'][i]['bowlteam']
                    overs = game['scorecard'][i]['overs']
                    batteam = game['scorecard'][i]['batteam']
                    runrate = game['scorecard'][i]['runrate']

                    print(
                        colors(
                            "\n{} - {} / {}({} Ovs)".format(
                                batteam, runs, wickets, overs), 32))
                    sleep(1)
                    print("\n--BATTING CARD--\n")
                    battCard(game, i)
                    sleep(1)
                    print("\n--BOWLING CARD--\n")
                    bowlCard(game, i)
                    sleep(1)
            except IndexError:
                pass
Esempio n. 10
0
def fun():
    #we enter our Twilio accoundSid and authToken(find it on twilio account settings)
    accountSid = "your accoundSid"
    authToken = "your authToken"
    # connecting to TWILIO API
    # twilioClient  = Client(accountSid, authToken)
    myTwilioNumber = "your twilio number"
    destCellPhone = "your mobile number"

    # url = "http://synd.cricbuzz.com/j2me/1.0/livematches.xml"
    # url = "https://www.cricbuzz.com/sitemap/index.xml"
    #to extract the matches
    cric = Cricbuzz()
    details = cric.matches()

    # print details
    # print "asdglavdlhavfhjsvlhvf.vsfksfjbsfjbsrfjbsdfjbsribfjsbfkefv"
    exit()
    #To filter out the None objects from details
    details = filter(None, details)
    message = "No match in progress"
    for i in details:
        if i["id"] == '8':
            # traversing i
            if 'mchstate' in i:
                if i['mchstate'] == 'inprogress':
                    id = i['id']
                    main = cric.livescore(id)
                    ms = main['batting']['score'][0]
                    if len(main['batting']['batsman'][0]) != 0 and len(
                            main['batting']['batsman'][1]) != 0:
                        bat1 = main['batting']['batsman'][0]
                        bat2 = main['batting']['batsman'][1]
                        bowl1 = main['bowling']['bowler'][0]
                        bowl2 = main['bowling']['bowler'][1]
                        message = i['srs'] + "      " + "Format: " + i[
                            'type'] + "\n \n" + "Score: " + main['batting'][
                                'team'] + " " + ms['runs'] + '/' + ms['wickets'] + " (" + ms[
                                    'overs'] + ")" + "\n \n" + bat1['name'] + ":" + bat1[
                                        'runs'] + "(" + bat1['balls'] + ")   " + bat2[
                                            'name'] + ":" + bat1['runs'] + "(" + bat2[
                                                'balls'] + ")" + "\n \n" + bowl1[
                                                    'name'] + ": overs-" + bowl1[
                                                        'overs'] + " wickets " + bowl1[
                                                            'wickets'] + "\n \n" + bowl2[
                                                                'name'] + ": overs- " + bowl2[
                                                                    'overs'] + " wickets " + bowl2[
                                                                        'wickets']
                    else:
                        message = "WICKET!!!!"

    #Generates the message
    notify2.init("Live Score")
    # shows notification on out desktop
    notify2.Notification("Match currently in progress:", message).show()
    # sends the notification to our mobile
    #myMessage = twilioClient.messages.create(body = "Match Currently in progress: " + message, from_=myTwilioNumber, to=destCellPhone)
    #shows notification after every 60 seconds
    time.sleep(60)
Esempio n. 11
0
def cric():
    c = Cricbuzz()
    matches = c.matches()
    for match in matches:
        print("Match:" + match['mchdesc'])
        print("Match Description:" + match['srs'])
        print("Match Type:" + match['type'])
        print("Match Status:" + match['status'])
        print("\n")
Esempio n. 12
0
def check(mid):
    """ To check is the match has already started or not"""

    c = Cricbuzz()
    matches = c.matches()
    for match in matches:
        if match['id'] == mid:
            return match['mchstate']
            break
Esempio n. 13
0
def fun():
    # we enter our Twilio accoundSid and authToken
    # accountSid = ""
    # authToken = ""
    # connecting to TWILIO API
    # twilioClient = Client(accountSid, authToken)
    # myTwilioNumber = ""
    # destCellPhone = ""

    # url = "http://synd.cricbuzz.com/j2me/1.0/livematches.xml"
    # to extract the matches
    cric = Cricbuzz()
    details = cric.matches()
    # print(details)
    # To filter out the None objects from details
    details = filter(None, details)
    message = "No match in progress"
    for i in details:
        # traversing i
        if 'mchstate' in i:
            # print('Series ==>' + i['srs'])  # List All Current Series
            if i['mchstate'] == 'inprogress' and i[
                    'srs'] == 'India tour of New Zealand 2020':
                # if i['mchstate'] == 'innings break':
                # if i['mchstate'] in ('inprogress','innings break'):
                id = i['id']
                main = cric.livescore(id)
                ms = main['batting']['score'][0]
                bat1 = main['batting']['batsman'][0]
                bat2 = main['batting']['batsman'][1]
                curr_bowler = main['bowling']['bowler'][0]
                # print(bat1['name'])
                # print(curr_bowler['name','overs','runs','wickets'])
                message = i['srs'] + "      " + "Format: " + i[
                    'type'] + "\n" + "Score: " + main['batting']['team'] + " " + ms[
                        'runs'] + '/' + ms['wickets'] + " (" + ms[
                            'overs'] + ")" + "\n" + bat1['name'] + ":" + bat1[
                                'runs'] + "(" + bat1['balls'] + ")   " + bat2[
                                    'name'] + ":" + bat2['runs'] + "(" + bat2[
                                        'balls'] + ")" + "\n" + curr_bowler[
                                            'name'] + ": " + curr_bowler[
                                                'overs'] + "-" + curr_bowler[
                                                    'runs'] + "-" + curr_bowler[
                                                        'wickets']
    # Generates the message
    print(message)
    # notify2.init("Live Score")
    baloontip.__init__('Live Score')
    # shows notification on out desktop
    # notify2.Notification("Match currently in progress:", message).show()
    n = baloontip.balloon_tip("Match currently in progress: ", message).show()
    # sends the notification to our mobile
    # myMessage = twilioClient.messages.create(body="Match Currently in progress: " + message, from_=myTwilioNumber,
    #                                          to=destCellPhone)
    # shows notification after every 60 seconds
    time.sleep(60)
def users():
    c = Cricbuzz()
    all_matches = c.matches()
    for match in all_matches:

        if match['mchstate'] == 'inprogress' or match[
                'mchstate'] == 'innings break':
            data = mongo.db.inprogress.insert(match)

    return render_template('result.html', result=mongo.db.inprogress.find())
Esempio n. 15
0
async def prev_match(ctx):
    c = Cricbuzz()
    matches = c.matches()
    for I in matches:
        if I['srs'] == 'Indian Premier League 2020' and I['mchstate'] == 'mom':
            embed = discord.Embed(
                title=f"{I['team1']['name']} vs {I['team2']['name']}",
                colour=discord.Colour.blue())
            embed.description = f"{I['status']}"
            await ctx.send(embed=embed)
Esempio n. 16
0
def call_pycricbuzz_get_id():
    c = Cricbuzz()
    matches = c.matches()
    for match in matches:
        if match['mchstate'] == 'inprogress':
            #match_status = match['status']
            if match['team1']['name'].lower(
            ) == 'india' or match['team2']['name'].lower() == 'india':
                match_id = match['id']
                return match_id
Esempio n. 17
0
def alldetail(request, id):
    c = Cricbuzz()
    #print (c.scorecard(match['id']))
    alldetail = c.scorecard(id)

    matches = c.matches()
    bat1 = 0
    bowl1 = 0
    fall_wickets1 = 0
    #return JsonResponse({"alldetail":alldetail})
    try:
        bat = alldetail['scorecard'][0]['batcard']
        bowl = alldetail['scorecard'][0]['bowlcard']
        fall_wickets = alldetail['scorecard'][0]['fall_wickets']
    except:
        pass
    try:
        bat1 = alldetail['scorecard'][1]['batcard']
        bowl1 = alldetail['scorecard'][1]['bowlcard']
        fall_wickets1 = alldetail['scorecard'][1]['fall_wickets']
    except:
        pass

    lscore = c.livescore(id)
    overin2 = 0
    overin3 = 0
    overin1 = 0
    overin4 = 0
    try:
        overin1 = lscore['batting']['score'][0]['overs']
        overin3 = lscore['bowling']['score'][0]['overs']
        overin2 = lscore['batting']['score'][1]['overs']
        overin4 = lscore['bowling']['score'][1]['overs']

    except:
        pass

    #return JsonResponse({"bat1":fall_wickets1})

    return render(
        request, "cric/scorecard2.html", {
            "alldetail": alldetail,
            "bat": bat,
            "bowl": bowl,
            "fall_wickets": fall_wickets,
            "bat1": bat1,
            "bowl1": bowl1,
            "fall_wickets1": fall_wickets1,
            "lscore": lscore,
            "overin2": overin2,
            "overin3": overin3,
            "overin1": overin1,
            "overin4": overin4,
            "matches": matches,
        })
Esempio n. 18
0
def match_info(request, id, src):
    '''c = Cricbuzz()
    #id=int(id)
    minfo = c.matchinfo(id)
    return render(request,"cric/matchinfo.html",{"minfo":minfo,"id":id})'''
    c = Cricbuzz()
    matches = c.matches()
    #print(json.dumps(matches, indent=4, sort_keys=True))
    return render(request, "cric/home.html", {
        "matches": matches,
    })
Esempio n. 19
0
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}"
Esempio n. 20
0
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")
Esempio n. 21
0
def send_updates(tournament, desktop_notification):
    while True:
        cricbuzz = Cricbuzz()
        matches = cricbuzz.matches()
        for match in matches:
            result = get_score(cricbuzz, match, tournament)
            if result:
                post_ifttt_webhook('cricket_info', result)
                if desktop_notification:
                    notify_desktop(result)
        print '-' * 20
        time.sleep(600)
Esempio n. 22
0
def circbuzz():
    c = Cricbuzz()
    matches = c.matches()
    newMatches = []
    for match in matches:
        try:
            if match['type'] == 'T20':
                newMatches.append(match)
        except:
            return "Error occured in interation"

    return json.dumps(newMatches, indent=4)
Esempio n. 23
0
async def ipl_poll(ctx):
    c = Cricbuzz()
    matches = c.matches()
    for I in matches:
        if I['srs'] == 'Indian Premier League 2020' and (
                I['mchstate'] == 'inprogress' or I['mchstate'] == 'preview'):
            embed = discord.Embed(
                title=
                f"IPL POLLING\n{I['team1']['name']} vs {I['team2']['name']}",
                colour=discord.Colour.blue())
            embed.description = f"{I['team1']['name']} : 1️⃣\n\n{I['team2']['name']} : 2️⃣ "
            await ctx.send(embed=embed)
Esempio n. 24
0
def listOfMatches():
    try:
        c = Cricbuzz()
        matches = c.matches()
        for match in matches:
            print(match['id'] + "  " + match['start_time'] + " " +
                  match['srs'])
        print(matches[0]['id'])
        return matches[0]['id']

    except:
        print("An exception occurred fetching list of matches")
Esempio n. 25
0
 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 preview():
    c = Cricbuzz()
    all_matches = c.matches()
    for match in all_matches:
        if match['mchstate'] == 'preview':
            if mongo.db.preview.find().count() > 0:
                mongo.db.preview.delete_one({'id': match['id']})
                result = mongo.db.preview.insert(match)

            else:
                result = mongo.db.preview.insert(match)

    return render_template("previewresult.html",
                           result=mongo.db.preview.find())
Esempio n. 27
0
def apitest(request):

    c = Cricbuzz()
    matches = c.matches()
    news = News.objects.all()
    img = Imag.objects.all()

    #print(json.dumps(matches, indent=4, sort_keys=True))
    #return JsonResponse({"daa":news})
    return render(request, "cric/index2.html", {
        "matches": matches,
        "news": news,
        "img": img,
    })
    '''c = Cricbuzz()
def complete():
    c = Cricbuzz()
    all_matches = c.matches()
    for match in all_matches:

        if match['mchstate'] == 'complete' or match['mchstate'] == 'mom':

            if mongo.db.completed.find().count() > 0:
                mongo.db.completed.delete_one({'id': match['id']})
                result = mongo.db.completed.insert(match)

            else:
                result = mongo.db.completed.insert(match)

    return render_template("pastresult.html", result=mongo.db.completed.find())
Esempio n. 29
0
def calculate_score():
    #for batsman
    players = []
    sixes = 0
    fours = 0
    runs = 0
    balls_faced = 0
    c = Cricbuzz()
    file = open('playerlist.txt', 'r')
    for line in file:
        players.append(line.strip())
    print(players)

    matches = c.matches()
    score_card = c.scorecard(match['id'])
Esempio n. 30
0
def fun():
    #we enter our Twilio accoundSid and authToken
    accountSid = "###############################"
    authToken = "###############################"
    # connecting to TWILIO API
    twilioClient = Client(accountSid, authToken)
    myTwilioNumber = "#"
    destCellPhone = "#"

    #url = "http://synd.cricbuzz.com/j2me/1.0/livematches.xml"
    #to extract the matches
    cric = Cricbuzz()
    details = cric.matches()

    #To filter out the None objects from details
    details = filter(None, details)
    message = "No match in progress"

    for i in details:
        # traversing i
        if 'mchstate' in i:
            if i['mchstate'] == 'inprogress':
                id = i['id']
                main = cric.livescore(id)
                ms = main['batting']['score'][0]
                bat1 = main['batting']['batsman'][0]
                bat2 = main['batting']['batsman'][1]
                #print(bat1['name'])
                message = i['srs'] + "      " + "Format: " + i[
                    'type'] + "\n" + "Score: " + main['batting'][
                        'team'] + " " + ms['runs'] + '/' + ms[
                            'wickets'] + " (" + ms['overs'] + ")" + "\n" + bat1[
                                'name'] + ":" + bat1['runs'] + "(" + bat1[
                                    'balls'] + ")   " + bat2[
                                        'name'] + ":" + bat1[
                                            'runs'] + "(" + bat2['balls'] + ")"

    #Generates the message
    notify2.init("Live Score")
    # shows notification on out desktop
    notify2.Notification("Match currently in progress:", message).show()
    # sends the notification to our mobile
    myMessage = twilioClient.messages.create(
        body="Match Currently in progress: " + message,
        from_=myTwilioNumber,
        to=destCellPhone)
    #shows notification after every 60 seconds
    time.sleep(60)
Esempio n. 31
0
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