Esempio n. 1
0
  def _SummonerDataToMessage(self, summoner_data, team_data):
    # Build a custom text response since the default card -> text is a bit
    # verbose.
    text_response = summoner_data['summoner']
    if summoner_data['username']:
      text_response = summoner_data['username'] + ' = ' + text_response
    if 'rank' in summoner_data:
      text_response += ', %s %s' % (
          summoner_data['region'].upper(), summoner_data['rank'])
    card = message_pb2.Card(
        header=message_pb2.Card.Header(
            title=summoner_data['summoner'],
            subtitle='%s %s, %s' %
            (summoner_data['region'].upper(),
             summoner_data.get('rank', 'Unranked'),
             summoner_data.get('username', 'HypeBot Pleb')),
            image={
                'url':
                    self._core.game.GetImageUrl(
                        'profileicon', '%d.png' %
                        summoner_data.get('profile_icon_id', 0))
            }))

    last_game_info = []
    win = '?'
    when = '?'
    # Checking is not None because "False" == a loss
    if summoner_data['last_game'].get('win') is not None:
      win = 'W' if summoner_data['last_game']['win'] else 'L'
    if summoner_data['last_game'].get('time'):
      when = util_lib.TimeDeltaToHumanDuration(
          arrow.now(self._core.timezone) - summoner_data['last_game']['time'])
    if summoner_data.get('penta'):
      last_game_info.append('PENTAKILL')
    if 'champion' in summoner_data['last_game']:
      last_game_info.append('%s: %s' % (summoner_data['last_game'].get(
          'type', 'Unknown'), summoner_data['last_game']['champion']))
    if 'fantasy_points' in summoner_data['last_game']:
      last_game_info.append('%.1fpts (%s ago, %s)' % (
          summoner_data['last_game']['fantasy_points'], when, win))
    if last_game_info:
      text_response += ' [%s]' % ', '.join(last_game_info)
      card.fields.add(title='Last Game', text=', '.join(last_game_info))

    if team_data:
      league = self._core.esports.leagues[team_data.team.league_id]
      team_text = '%s: %d%s' % (
          team_data.team.name, team_data.rank,
          inflect_lib.Ordinalize(team_data.rank))
      card.fields.add(title=league.name, text=team_text)
      text_response += ' [(%s) %s]' % (league.name, team_text)
    if not card.fields:
      card.fields.add(text='A very dedicated player.')

    card.fields.add(
        buttons=[{
            'text': 'u.gg',
            'action_url': _U_GG.format(**summoner_data),
        }])
    return message_pb2.Message(text=[text_response], card=card)
Esempio n. 2
0
    def _Handle(self, channel: channel_pb2.Channel, user: user_pb2.User,
                target_user: user_pb2.User) -> hype_types.CommandResponse:
        now = arrow.utcnow()
        recent_transactions = self._core.bank.GetTransactions(target_user)
        if not recent_transactions:
            return '%s doesn\'t believe in the HypeCoin economy.' % target_user.display_name

        responses = [
            'Recent HypeCoin Transactions for %s' % target_user.display_name
        ]
        for tx in recent_transactions[:5]:
            amount = util_lib.FormatHypecoins(tx.amount)
            if tx.amount < 0:
                amount = util_lib.Colorize(f'{amount}', 'red')
                direction = 'to'
            elif tx.amount > 0:
                amount = util_lib.Colorize(f'+{amount}', 'green')
                direction = 'from'
            else:
                amount = amount
                direction = 'with'

            ago = util_lib.TimeDeltaToHumanDuration(
                now - arrow.get(tx.create_time.ToSeconds()))
            responses.append(
                f'{amount} {direction} {tx.counterparty.display_name} '
                f'{ago} ago [{tx.details}]')
        return responses
Esempio n. 3
0
 def _SummonerDataToText(self, summoner_data, team_data) -> Text:
     info = summoner_data['summoner']
     if summoner_data['username']:
         info = summoner_data['username'] + ' = ' + info
     extra_info = []
     # Checking is not None because "False" == a loss
     if summoner_data['last_game'].get('win') is not None:
         win = 'W' if summoner_data['last_game']['win'] else 'L'
     else:
         win = '?'
     if summoner_data['last_game'].get('time'):
         now = arrow.now(self._core.timezone)
         delta = now - summoner_data['last_game']['time']
         when = util_lib.TimeDeltaToHumanDuration(delta)
     if summoner_data.get('penta'):
         extra_info.append('PENTAKILL')
     if 'rank' in summoner_data:
         extra_info.append(summoner_data['rank'] + ' (' +
                           summoner_data['region'].upper() + ')')
     if 'champion' in summoner_data['last_game']:
         extra_info.append('%s: %s' % (summoner_data['last_game'].get(
             'type', 'Unknown'), summoner_data['last_game']['champion']))
     if 'fantasy_points' in summoner_data['last_game']:
         extra_info.append(
             '%.1fpts (%s ago, %s)' %
             (summoner_data['last_game']['fantasy_points'], when, win))
     if extra_info:
         info += ' [' + ', '.join(extra_info) + ']'
     if team_data:
         rank = team_data['team_rank']
         info += ' [(%s) %s, %d%s]' % (team_data['league_abbrev'],
                                       team_data['team_name'], rank,
                                       inflect_lib.Ordinalize(rank))
     return info
Esempio n. 4
0
  def _Handle(self, channel, user, account, tx_user):
    tx_user = tx_user or user
    if tx_user == 'me':
      tx_user = user
    tx_user = _GetUserAccount(tx_user, account)
    now = arrow.utcnow()
    recent_transactions = self._core.bank.GetTransactions(tx_user)
    if not recent_transactions:
      return '%s doesn\'t believe in the HypeCoin economy.' % tx_user

    responses = ['Recent HypeCoin Transactions for %s' % tx_user]
    for tx in recent_transactions[:5]:
      if tx_user == tx.get('source'):
        base_tx_description = ' {} to {} %s ago [%s]'.format(
            util_lib.Colorize('-%s', 'red'), tx.get('destination', 'unknown'))
      else:
        base_tx_description = ' {} from {} %s ago [%s]'.format(
            util_lib.Colorize('+%s', 'green'), tx.get('source', 'unknown'))

      time_delta = now - arrow.get(tx.get('ts', now.timestamp))
      time_str = util_lib.TimeDeltaToHumanDuration(
          time_delta) if time_delta else '??'

      tx_description = base_tx_description % (
          util_lib.FormatHypecoins(tx['amount']), time_str,
          tx.get('details', 'Unknown'))
      responses.append(tx_description)
    return responses
Esempio n. 5
0
 def _LotteryWarningCallback(self, remaining=None):
   logging.info('Running lottery warning callback.')
   warning_str = ''
   if remaining is not None:
     warning_str += 'The lottery winner will be drawn in %s! ' % (
         util_lib.TimeDeltaToHumanDuration(remaining))
   pool = self._core.bets.LookupBets(self._game.name, resolver=self._core.nick)
   coins, item = self._game.ComputeCurrentJackpot(pool)
   warning_str += 'Current jackpot is %s and a(n) %s' % (
       util_lib.FormatHypecoins(coins), item.human_name)
   self._Reply(self._core.default_channel, warning_str)
Esempio n. 6
0
 def _LotteryWarningCallback(self, remaining=None):
     logging.info('Running lottery warning callback.')
     warning_str = ''
     if remaining is not None:
         warning_str += 'The lottery winner will be drawn in %s! ' % (
             util_lib.TimeDeltaToHumanDuration(remaining))
     pool = self._core.bets.LookupBets(self._game.name,
                                       resolver=self._core.name.lower())
     coins, item = self._game.ComputeCurrentJackpot(pool)
     item_str = inflect_lib.AddIndefiniteArticle(item.human_name)
     warning_str += 'Current jackpot is %s and %s' % (
         util_lib.FormatHypecoins(coins), item_str)
     self._core.PublishMessage('lottery', warning_str)
Esempio n. 7
0
    def _SummonerDataToCard(
            self, summoner_data,
            team_data):  # -> contextual_addon_pb2.ContextualAddOnMarkup.Card:
        # TODO(zaw): Combine with _SummonerDataToText.
        card = contextual_addon_pb2.ContextualAddOnMarkup.Card(
            header=contextual_addon_pb2.ContextualAddOnMarkup.Card.CardHeader(
                title=summoner_data['summoner'],
                subtitle='%s %s, %s' %
                (summoner_data['region'].upper(),
                 summoner_data.get('rank', 'Unranked'),
                 summoner_data.get('hype_title', 'HypeBot Pleb')),
                image_url=self._core.game.GetImageUrl(
                    'profileicon', '%d.png' %
                    summoner_data.get('profile_icon_id', 0))))
        section = card.sections.add()

        last_game_info = []
        # Checking is not None because "False" == a loss
        if summoner_data['last_game'].get('win') is not None:
            win = 'W' if summoner_data['last_game']['win'] else 'L'
        else:
            win = '?'
        if summoner_data['last_game'].get('time'):
            now = arrow.now(self._core.timezone)
            delta = now - summoner_data['last_game']['time']
            when = util_lib.TimeDeltaToHumanDuration(delta)
        if summoner_data.get('penta'):
            last_game_info.append('PENTAKILL')
        if 'champion' in summoner_data['last_game']:
            last_game_info.append('%s: %s' % (summoner_data['last_game'].get(
                'type', 'Unknown'), summoner_data['last_game']['champion']))
        if 'fantasy_points' in summoner_data['last_game']:
            last_game_info.append(
                '%.1fpts (%s ago, %s)' %
                (summoner_data['last_game']['fantasy_points'], when, win))

        if team_data:
            widget = section.widgets.add()
            widget.key_value.top_label = 'Grumble Team'
            rank = team_data['team_rank']
            widget.key_value.content = '(%s) %s, %d%s' % (
                team_data['league_abbrev'], team_data['team_name'], rank,
                inflect_lib.Ordinalize(rank))
        if last_game_info:
            widget = section.widgets.add()
            widget.key_value.top_label = 'Last Game'
            widget.key_value.content = ', '.join(last_game_info)
        if not section.widgets:
            widget = section.widgets.add()
            widget.text_paragraph.text = 'A very dedicated player.'
        return card
Esempio n. 8
0
    def _BuildHeadlineCard(self, header_text, raw_results):
        card = message_pb2.Card(header=message_pb2.Card.Header(
            title=header_text, image=self._core.news.icon),
                                visible_fields_count=6)

        sorted_results = sorted(raw_results,
                                key=lambda x: x.get('pub_date', arrow.get(0)),
                                reverse=True)
        for article in sorted_results:
            field = message_pb2.Card.Field(text=article['title'])
            if article.get('pub_date'):
                field.title = 'Published %s ago' % util_lib.TimeDeltaToHumanDuration(
                    arrow.utcnow() - arrow.get(article['pub_date']))
            source = article.get('source')
            if source and source != self._core.news.source:
                field.bottom_text = source
            card.fields.append(field)
            card.fields.append(
                message_pb2.Card.Field(buttons=[
                    message_pb2.Card.Field.Button(text='Read article',
                                                  action_url=article['url'])
                ]))

        return card
Esempio n. 9
0
    def _Handle(self, unused_channel, unused_user, detailed, region):
        endpoint = 'us'
        if region:
            region = region.upper()
            endpoint = 'states'
        region = region or 'USA'
        raw_results = self._core.proxy.FetchJson(self._API_URL + endpoint)
        logging.info('CovidAPI raw_result: %s', raw_results)
        if not raw_results:
            return 'Unknown region, maybe everyone should move there.'

        state_data = {}
        if len(raw_results) == 1:
            state_data = raw_results[0]
        else:
            state_data = [
                state for state in raw_results if state.get('state') == region
            ][0]

        if not state_data:
            return 'Unknown region, maybe everyone should move there.'

        # Raw data
        cases, new_cases = self._ParseResult(state_data, 'positive')
        tests, new_tests = self._ParseResult(state_data, 'totalTestResults')
        hospitalized, new_hospitalizations = self._ParseResult(
            state_data, 'hospitalizedCurrently')
        ventilators, _ = self._ParseResult(state_data, 'onVentilatorCurrently')
        icu_patients, _ = self._ParseResult(state_data, 'inIcuCurrently')
        deaths, new_deaths = self._ParseResult(state_data, 'death')
        population = self._core.population.GetPopulation(region)

        if detailed:
            fields = []
            info_field_fn = functools.partial(self._InfoField,
                                              population=population)
            if cases:
                fields.append(
                    info_field_fn('Confirmed cases', cases, new_cases))
            if tests:
                fields.append(
                    info_field_fn('Tests administered',
                                  tests,
                                  new_tests,
                                  up_is_good=True))
            if hospitalized:
                fields.append(
                    info_field_fn(
                        'Hospitalized',
                        hospitalized,
                        new_hospitalizations,
                    ))
            if icu_patients:
                fields.append(info_field_fn('ICU patients', icu_patients))
            if ventilators:
                fields.append(info_field_fn('Ventilators in use', ventilators))
            if deaths:
                fields.append(info_field_fn('Deaths', deaths, new_deaths))

            update_time = state_data.get('dateChecked') or state_data.get(
                'lastModified')
            update_time_str = 'some time'
            if update_time:
                update_timedelta = arrow.utcnow() - arrow.get(update_time)
                update_time_str = util_lib.TimeDeltaToHumanDuration(
                    update_timedelta)

            fields.append(
                message_pb2.Card.Field(buttons=[
                    message_pb2.Card.Field.Button(
                        text='Source', action_url='https://covidtracking.com/')
                ]))
            return message_pb2.Card(header=message_pb2.Card.Header(
                title='%s COVID-19 Statistics' %
                self._core.population.GetNameForRegion(region),
                subtitle='Updated %s ago' % update_time_str),
                                    fields=fields,
                                    visible_fields_count=4)

        deaths, descriptor = inflect_lib.Plural(deaths, 'death').split()
        death_str = '{:,} {}'.format(int(deaths), descriptor)

        cases, descriptor = inflect_lib.Plural(
            cases, 'confirmed cases').split(maxsplit=1)
        case_str = '{:,} {}'.format(int(cases), descriptor)

        tests, descriptor = inflect_lib.Plural(tests, 'test').split()
        percent_tested = float(tests) / population
        test_str = '{:,} [{:.1%} of the population] {}'.format(
            int(tests), percent_tested, descriptor)

        return '%s has %s (%s) with %s administered.' % (
            region or 'The US', case_str, death_str, test_str)