Daily random pokemon

OK all, I have taken this as far as I can go … I promise now I will pull it togther and post on Git, you have much of it above.

The code for GUI is now this (of course you will need many of the code behind like sensors, automations, scripts) …

type: vertical-stack
cards:
  - type: horizontal-stack
    cards:
      - type: custom:mushroom-template-card
        entity: sensor.random_pokemon
        primary: Previous Pokemon
        secondary: Show Previous Pokemon
        icon: mdi:backburger
        icon_color: red
        tap_action:
          action: none
        hold_action:
          action: call-service
          service: script.get_pokemon
          data:
            pokemode: Decrement
          target: {}
      - type: custom:mushroom-template-card
        entity: sensor.random_pokemon
        primary: Grab a Pokemon!
        secondary: Hold to Grab a random Pokemon
        icon: mdi:pokeball
        icon_color: red
        tap_action:
          action: none
        hold_action:
          action: call-service
          service: script.get_pokemon
          data:
            pokemode: Random
          target: {}
      - type: custom:mushroom-select-card
        entity: input_select.pokedex
        icon: mdi:pokemon-go
        icon_color: red
        name: Select A Pokemon
        layout: horizontal
        hold_action:
          action: call-service
          service: script.get_pokemon
          data:
            pokemode: Name
          target: {}
      - type: custom:mushroom-template-card
        entity: sensor.random_pokemon
        primary: Next Pokemon
        secondary: Show Next Pokemon
        icon: mdi:forwardburger
        icon_color: red
        tap_action:
          action: none
        hold_action:
          action: call-service
          service: script.get_pokemon
          data:
            pokemode: Increment
          target: {}
  - type: horizontal-stack
    cards:
      - type: vertical-stack
        cards:
          - type: custom:mushroom-title-card
            entity: sensor.random_pokemon
            title: '{{state_attr(''sensor.random_pokemon'',''name'') | capitalize}}'
            subtitle: ''
            title_tap_action:
              action: none
          - type: markdown
            content: >
              {% set fv = namespace(engfv=[]) %} {% for fte in
              state_attr('sensor.pokemon_species','flavor_text_entries') -%} {%
              if fte.language.name == 'en' -%}
                  {% set fv.engfv = fv.engfv + [fte.flavor_text | replace('\n',' ') | replace('\f',' ')] %}
              {% endif %} {%- endfor %} {{ fv.engfv[0] }}
          - type: custom:config-template-card
            entities:
              - sensor.random_pokemon
            card:
              type: picture-entity
              entity: sensor.random_pokemon
              show_name: false
              show_state: false
              image: >-
                ${'http://192.168.2.245:8123/local/Pokemon/Sprites/Master/' +
                states['sensor.random_pokemon'].attributes.id + '.png'}


          - type: markdown
            content: |
              Pokémon Images & Names © 1995-2023 Nintendo/Game Freak.
      - type: vertical-stack
        cards:
          - type: custom:mushroom-title-card
            title: Data
            subtitle: ''
            title_tap_action:
              action: none
          - type: horizontal-stack
            cards:
              - type: markdown
                content: >-
                  ## Information

                  National No: {{state_attr('sensor.random_pokemon','id') }}

                  Height: {{state_attr('sensor.random_pokemon','height')/10}} m

                  Weight: {{state_attr('sensor.random_pokemon','weight')/10 }}
                  kg

                  Base Experience:
                  {{state_attr('sensor.random_pokemon','base_experience') }}

                  ## Held Items

                  {% if state_attr("sensor.random_pokemon","held_items") | count
                  > 0 %} {% for hi in
                  state_attr("sensor.random_pokemon","held_items") -%}
                    {{ hi.item.name }}
                  {%- endfor %} {% else %}
                    {{'No Held Items'}}
                  {% endif %}
              - type: markdown
                content: >-
                  ## Types

                  {% for tp in state_attr("sensor.random_pokemon","types") -%}
                    {{ tp.type.name }}
                  {% endfor %}

                  ## Abilities

                  {% for ab in state_attr("sensor.random_pokemon","abilities")
                  -%}
                    {{ ab.ability.name }}
                  {% endfor %}
          - type: custom:mushroom-title-card
            title: Moves
            subtitle: ''
            title_tap_action:
              action: none
          - type: custom:stack-in-card
            mode: vertical
            style: 'ha-card {overflow-y: scroll!important; height: 350px}'
            cards:
              - type: custom:auto-entities
                card:
                  type: grid
                  square: false
                  columns: 4
                card_param: cards
                filter:
                  template: |-
                    {% for mv in state_attr("sensor.random_pokemon","moves") -%}
                      {{
                        {
                          'type': 'custom:mushroom-template-card',
                          'primary': mv.move.name,
                          'secondary': '',
                          'icon_type': 'none',
                          'tap_action': 'none',
                          'style': 'ha-card {text-align: center; box-shadow: none}'
                        }
                       }},
                     {%- endfor %}
      - type: vertical-stack
        cards:
          - type: custom:mushroom-title-card
            title: Statistics
            subtitle: ''
            title_tap_action:
              action: none
          - type: custom:stack-in-card
            mode: vertical
            cards:
              - type: horizontal-stack
                cards:
                  - type: custom:card-templater
                    entities:
                      - sensor.random_pokemon
                    card:
                      type: custom:gauge-card
                      entity: sensor.pokemon_base_stats
                      attribute: hp
                      measurement: ''
                      title: HP
                      min: 0
                      max_template: >-
                        {{ (state_attr("sensor.random_pokemon","stats") |
                        map(attribute="base_stat") | max) * 1.1 }}
                      severity:
                        red_template: >-
                          {{ (state_attr("sensor.random_pokemon","stats") |
                          map(attribute="base_stat") | max) * 0.8 }}
                        green_template: >-
                          {{ (state_attr("sensor.random_pokemon","stats") |
                          map(attribute="base_stat") | max) * 0.3 }}
                        amber_template: >-
                          {{ (state_attr("sensor.random_pokemon","stats") |
                          map(attribute="base_stat") | max) * 0.6 }}
                  - type: custom:card-templater
                    entities:
                      - sensor.random_pokemon
                    card:
                      type: custom:gauge-card
                      entity: sensor.pokemon_base_stats
                      attribute: attack
                      measurement: ''
                      title: Attack
                      min: 0
                      max_template: >-
                        {{ (state_attr("sensor.random_pokemon","stats") |
                        map(attribute="base_stat") | max) * 1.1 }}
                      severity:
                        red_template: >-
                          {{ (state_attr("sensor.random_pokemon","stats") |
                          map(attribute="base_stat") | max) * 0.8 }}
                        green_template: >-
                          {{ (state_attr("sensor.random_pokemon","stats") |
                          map(attribute="base_stat") | max) * 0.3 }}
                        amber_template: >-
                          {{ (state_attr("sensor.random_pokemon","stats") |
                          map(attribute="base_stat") | max) * 0.6 }}
              - type: horizontal-stack
                cards:
                  - type: custom:card-templater
                    entities:
                      - sensor.random_pokemon
                    card:
                      type: custom:gauge-card
                      entity: sensor.pokemon_base_stats
                      attribute: defense
                      measurement: ''
                      title: Defense
                      min: 0
                      max_template: >-
                        {{ (state_attr("sensor.random_pokemon","stats") |
                        map(attribute="base_stat") | max) * 1.1 }}
                      severity:
                        red_template: >-
                          {{ (state_attr("sensor.random_pokemon","stats") |
                          map(attribute="base_stat") | max) * 0.8 }}
                        green_template: >-
                          {{ (state_attr("sensor.random_pokemon","stats") |
                          map(attribute="base_stat") | max) * 0.3 }}
                        amber_template: >-
                          {{ (state_attr("sensor.random_pokemon","stats") |
                          map(attribute="base_stat") | max) * 0.6 }}
                  - type: custom:card-templater
                    entities:
                      - sensor.random_pokemon
                    card:
                      type: custom:gauge-card
                      entity: sensor.pokemon_base_stats
                      attribute: special-attack
                      measurement: ''
                      title: Special Attack
                      min: 0
                      max_template: >-
                        {{ (state_attr("sensor.random_pokemon","stats") |
                        map(attribute="base_stat") | max) * 1.1 }}
                      severity:
                        red_template: >-
                          {{ (state_attr("sensor.random_pokemon","stats") |
                          map(attribute="base_stat") | max) * 0.8 }}
                        green_template: >-
                          {{ (state_attr("sensor.random_pokemon","stats") |
                          map(attribute="base_stat") | max) * 0.3 }}
                        amber_template: >-
                          {{ (state_attr("sensor.random_pokemon","stats") |
                          map(attribute="base_stat") | max) * 0.6 }}
              - type: horizontal-stack
                cards:
                  - type: custom:card-templater
                    entities:
                      - sensor.random_pokemon
                    card:
                      type: custom:gauge-card
                      entity: sensor.pokemon_base_stats
                      attribute: special-defense
                      measurement: ''
                      title: Special Defense
                      min: 0
                      max_template: >-
                        {{ (state_attr("sensor.random_pokemon","stats") |
                        map(attribute="base_stat") | max) * 1.1 }}
                      severity:
                        red_template: >-
                          {{ (state_attr("sensor.random_pokemon","stats") |
                          map(attribute="base_stat") | max) * 0.8 }}
                        green_template: >-
                          {{ (state_attr("sensor.random_pokemon","stats") |
                          map(attribute="base_stat") | max) * 0.3 }}
                        amber_template: >-
                          {{ (state_attr("sensor.random_pokemon","stats") |
                          map(attribute="base_stat") | max) * 0.6 }}
                  - type: custom:card-templater
                    entities:
                      - sensor.random_pokemon
                    card:
                      type: custom:gauge-card
                      entity: sensor.pokemon_base_stats
                      attribute: speed
                      measurement: ''
                      title: Speed
                      min: 0
                      max_template: >-
                        {{ (state_attr("sensor.random_pokemon","stats") |
                        map(attribute="base_stat") | max) * 1.1 }}
                      severity:
                        red_template: >-
                          {{ (state_attr("sensor.random_pokemon","stats") |
                          map(attribute="base_stat") | max) * 0.8 }}
                        green_template: >-
                          {{ (state_attr("sensor.random_pokemon","stats") |
                          map(attribute="base_stat") | max) * 0.3 }}
                        amber_template: >-
                          {{ (state_attr("sensor.random_pokemon","stats") |
                          map(attribute="base_stat") | max) * 0.6 }}
          - type: custom:mushroom-title-card
            title: Sprites
            subtitle: ''
            title_tap_action:
              action: none
          - type: vertical-stack
            cards:
              - type: custom:stack-in-card
                mode: vertical
                cards:
                  - type: horizontal-stack
                    cards:
                      - type: vertical-stack
                        cards:
                          - type: custom:mushroom-template-card
                            picture: >
                              /local/Pokemon/Sprites/front/{{state_attr('sensor.random_pokemon','id')}}.png
                            primary: Front
                            secondary: ''
                            layout: horizontal
                            tap_action:
                              action: none
                            hold_action:
                              action: none
                            double_tap_action:
                              action: none
                          - type: custom:mushroom-template-card
                            picture: >
                              /local/Pokemon/Sprites/back/{{state_attr('sensor.random_pokemon','id')}}.png
                            primary: Back
                            secondary: ''
                            layout: horizontal
                            tap_action:
                              action: none
                            hold_action:
                              action: none
                            double_tap_action:
                              action: none
                          - type: custom:mushroom-template-card
                            picture: >
                              /local/Pokemon/Sprites/front/shiny/{{state_attr('sensor.random_pokemon','id')}}.png
                            primary: Front Shiny
                            secondary: ''
                            layout: horizontal
                            tap_action:
                              action: none
                            hold_action:
                              action: none
                            double_tap_action:
                              action: none
                          - type: custom:mushroom-template-card
                            picture: >
                              /local/Pokemon/Sprites/back/shiny/{{state_attr('sensor.random_pokemon','id')}}.png
                            primary: Back Shiny
                            secondary: ''
                            layout: horizontal
                            tap_action:
                              action: none
                            hold_action:
                              action: none
                            double_tap_action:
                              action: none
                      - type: vertical-stack
                        cards:
                          - type: custom:mushroom-template-card
                            picture: >
                              {% if
                              state_attr("sensor.random_pokemon","sprites").front_female[0]
                              is defined %}
                                /local/Pokemon/Sprites/front/female/{{state_attr("sensor.random_pokemon","id")}}.png
                              {% else %}
                                /local/Pokemon/Sprites/0.png
                              {% endif %}
                            primary: Front Female
                            secondary: ''
                            layout: horizontal
                            tap_action:
                              action: none
                            hold_action:
                              action: none
                            double_tap_action:
                              action: none
                          - type: custom:mushroom-template-card
                            picture: >
                              {% if
                              state_attr("sensor.random_pokemon","sprites").back_female[0]
                              is defined %}
                                /local/Pokemon/Sprites/back/female/{{state_attr("sensor.random_pokemon","id")}}.png
                              {% else %}
                                /local/Pokemon/Sprites/0.png
                              {% endif %}
                            primary: Back Female
                            secondary: ''
                            layout: horizontal
                            tap_action:
                              action: none
                            hold_action:
                              action: none
                            double_tap_action:
                              action: none
                          - type: custom:mushroom-template-card
                            picture: >
                              {% if
                              state_attr("sensor.random_pokemon","sprites").front_shiny_female[0]
                              is defined %}
                                /local/Pokemon/Sprites/back/female/shiny/{{state_attr("sensor.random_pokemon","id")}}.png
                              {% else %}
                                /local/Pokemon/Sprites/0.png
                              {% endif %}
                            primary: Front Shiny Female
                            secondary: ''
                            layout: horizontal
                            tap_action:
                              action: none
                            hold_action:
                              action: none
                            double_tap_action:
                              action: none
                          - type: custom:mushroom-template-card
                            picture: >
                              {% if
                              state_attr("sensor.random_pokemon","sprites").back_shiny_female[0]
                              is defined %}
                                /local/Pokemon/Sprites/back/female/shiny/{{state_attr("sensor.random_pokemon","id")}}.png
                              {% else %}
                                /local/Pokemon/Sprites/0.png
                              {% endif %}
                            primary: Back Shiny Female
                            secondary: ''
                            layout: horizontal
                            tap_action:
                              action: none
                            hold_action:
                              action: none
                            double_tap_action:
                              action: none

1 Like

I’m a little confused about the sensor.pokemon_species entity you have referenced. Did I miss adding that to the config somewhere?

I am almost done with the Github writeup. It I will post in an hour or so.

1 Like

Here you go:

1 Like

@shirasp Yes. Some of the data and text descriptions need to be retrieved in a second sensor as it is a different REST call. I think I captured most everything and put that into the Git posting I just made.

1 Like

Thanks very much for the detailed post! I have added all 3 of the rest sensors to my config, and I got the sprite pictures and input selects/automations/scripts, but I am still having trouble with the sensor.pokemon_species. I cannot get the flavor text to populate at all, and I have tried with multiple pokemon (including the Pikachu which you used in your example). Any chance theres something obviously wrong with my config?

  - platform: rest
    name: Pokemon Species
    scan_interval: 86400
    resource_template: "{{ state_attr('sensor.random_pokemon','species').url }}"
    value_template: "{{ now() }}"
    json_attributes:
      - base_happiness
      - capture_rate
      - color
      - egg_groups
      - evolution_chain
      - evolves_from_species
      - flavor_text_entries
      - form_descriptions
      - forms_switchable
      - gender_rate
      - genera
      - generation
      - growth_rate
      - habitat
      - has_gender_differences
      - hatch_counter
      - id
      - is_baby
      - is_legendary
      - is_mythical
      - name
      - shape
      - varieties
      - names
      - order

In the template editior, I tried playing around with it and i just get an error message for both of these:

 {{ state_attr("sensor.pokemon_species","flavor_text_entries") }}

(both with " and ’ around the entities)

{% set fv = namespace(engfv=[]) %} {% for fte in
              state_attr('sensor.pokemon_species','flavor_text_entries') -%} {%
              if fte.language.name == 'en' -%}
                  {% set fv.engfv = fv.engfv + [fte.flavor_text | replace('\n',' ') | replace('\f',' ')] %}
              {% endif %} {%- endfor %} {{ fv.engfv[0] }}

Error Messsage: TypeError: ‘NoneType’ object is not iterable

Can you use developer state tools and make sure the sensor exists and is that name? And if it does exist does another attribute have values like name?

It is also possible that the sensor has never been created because it is based on the other sensor. So what does this yield in developer template?

"{{ state_attr('sensor.random_pokemon','species').url }}"

It that looks correct, I would try to manyally run the HA update entity service in developer and see if it fixes it. YOU can also surf to that URL if it returns something and look at the JSON and be sure it is returning something.

UPDATE: Mine is not returning anything either now although it worked yesterday. Let me investigate, possibly they changed something

UPDATE: It looks like it does not update properly because of the template. I went to Developer ->States and selected it and forced a refresh there and it reloaded. Possibly I have to put this into templates or set the update differently.

That is the issue, it is not updating when the random_pokemon sensor changes:

image

This issuse I believe is a direct result of this:

My sensor.random_pokemon had two entries and only the _2 one was correct. I do not understand why this is happening in HA (what programmer though it was smart to secretly add “_2” to the “good” one, assuming you had not already used the name in something else.


I have asked a question on that group to see how to fix this as the GUI does not allow me to delete them.

OK, well. I did a reboot of the server. Then a hard reload of the page once it was rebooted, then I have to update the random_pokemon entity and then it all started working again. I will need to think through this but nothing I can do I d not think. No programmer should write this way.

Anything _2, _3 … should be old ones, not the new ones as any scripts, templates or automations break as happened here.

Hmm, I don’t have anything with a _2 on it, and I also don’t have sensor.pokemon_species when I search in the developer tools → states or template. Its so weird becuase I definitely have it in the config file.
I’ll try rebooting and see what happens

Yes. DO that and then check logs … it could be that sensor.pokemon_species gave you an error because sensor.random_pokemon did not have the URL (yet). That is what happened on my reboot.

Did you ever getthis working? I had some additional input from core folks about REST sensors and the “_2” and such naming. I decided to add unique_id to all the sensors and I just set that to their names … as in for the main sensor:

- platform: rest
  name: Random Pokemon
  unique_id: sensor.random_pokemon
  scan_interval: 360000
  resource_template: >
      {% if states('input_select.select_pokemon_mode') == 'Increment' %}
        https://pokeapi.co/api/v2/pokemon/{{ state_attr('sensor.random_pokemon','id') + 1 }}
      {% elif states('input_select.select_pokemon_mode') == 'Decrement' %}
        https://pokeapi.co/api/v2/pokemon/{{ state_attr('sensor.random_pokemon','id') - 1 }}
      {% elif states('input_select.select_pokemon_mode') == 'Name' %}
        https://pokeapi.co/api/v2/pokemon/{{ states('input_select.pokedex') }}
      {% else %}
        https://pokeapi.co/api/v2/pokemon/{{ range(1, 1008) | random }}
      {% endif %}
  value_template: "{{ value_json.name }}"
  json_attributes:
    - abilities
    - base_experience
    - forms
    - game_indicies
    - height
    - held_items
    - id
    - is_default
    - location_area_encounters
    - moves
    - name
    - order
    - past_types
    - species
    - sprites
    - stats
    - types
    - weight

Now I do not get “_2” issues anymore as any changes made do does not create the “_2” things.

BUT … there is still one issue I see that could be your issue. Because sensor.pokemon_species is dependent on senor.random_pokemon it must be created at least once through running a reload of REST sesnors after reboot. Not sure if this will happen between multiple reboots (I hate to restart things) but I will see today. If it is, we will need to add an automation or something to say after one sensor is loaded, update the other.

I also noted that I need to put logic in for some Sprites that outputs the “?” icon when none exist for back or shiny. I only did the female ones.

image

I’m having issues with the sensor.pokemon_species being created. I followed the github and copy pasted all the sensor yaml. I tried reloading rest sensors after a reboot but maybe I’m doing something wrong. I do see this in my logs

Logger: homeassistant.helpers.event
Source: helpers/template.py:575
First occurred: 9:12:53 AM (1 occurrences)
Last logged: 9:12:53 AM

Error while processing template: Template<template=({% set fv = namespace(engfv=[]) %} {% for fte in state_attr('sensor.pokemon_species','flavor_text_entries') -%} {% if fte.language.name == 'en' -%} {% set fv.engfv = fv.engfv + [fte.flavor_text | replace('\n',' ') | replace('\f',' ')] %} {% endif %} {%- endfor %} {{ fv.engfv[0] }}) renders=2>
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 573, in async_render
    render_result = _render_with_context(self.template, compiled, **kwargs)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 2364, in _render_with_context
    return template.render(**kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/jinja2/environment.py", line 1301, in render
    self.environment.handle_exception()
  File "/usr/local/lib/python3.12/site-packages/jinja2/environment.py", line 936, in handle_exception
    raise rewrite_traceback_stack(source=source)
  File "<template>", line 1, in top-level template code
TypeError: 'NoneType' object is not iterable

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 699, in async_render_to_info
    render_info._result = self.async_render(
                          ^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 575, in async_render
    raise TemplateError(err) from err
homeassistant.exceptions.TemplateError: TypeError: 'NoneType' object is not iterable