Repository: PokemonGoF/PokemonGo-Bot

Issue:
Telegram bot integration
### Short Description

Telegram bot integration for remote progress updates
### Possible solution

Integrate a telegram bot feeding mechanism so that users can see their bots progress while away
### How it would help others

Users will be able to remotely check progress and see if bot is active and request basic stat updates: active time, XP gained, stardust gained, pokemons caught, XP per hour, stardust per hour, pokemons per hour, item list, pokemon list ordered by highest cp, iv, time, etc.

*by the way, many thanks for the effort you are putting in. Great experience so far.



Discussion:
[PokemonGo-Bot-Telegram](https://github.com/askovpen/PokemonGo-Bot-Telegram)

that's great! Any chance of instructions? Guessing put the .py file where you want, add the parameters in the config file. Then what?

i added instructions

much appreciated, thanks!

@askovpen That's great solution if we want to keep things separate, but it uses files and etc. For example, if we have distributed Docker configuration -- it would not be convenient to manage those things.
I think that in terms of original request maybe it would be better to implement Telegram logging handler. By the way, it is very easy because it is almost done already: https://github.com/python-telegram-bot/python-telegram-bot
This way we may selectively send some logging messages to Telegram or buffer them and send in bulk.

plugin for bot: https://github.com/askovpen/telegram-pgo-plugin


Resolving patch:
diff --git a/pokemongo_bot/cell_workers/__init__.py b/pokemongo_bot/cell_workers/__init__.py
--- a/pokemongo_bot/cell_workers/__init__.py
+++ b/pokemongo_bot/cell_workers/__init__.py
@@ -23,3 +23,4 @@
 from update_web_inventory import UpdateWebInventory
 from random_alive_pause import RandomAlivePause
 from show_best_pokemon import ShowBestPokemon
+from telegram_task import TelegramTask
diff --git a/pokemongo_bot/cell_workers/telegram_task.py b/pokemongo_bot/cell_workers/telegram_task.py
new file mode 100644
--- /dev/null
+++ b/pokemongo_bot/cell_workers/telegram_task.py
@@ -0,0 +1,72 @@
+# -*- coding: utf-8 -*-
+import telegram
+import os
+import json
+from pokemongo_bot.base_task import BaseTask
+from pokemongo_bot.base_dir import _base_dir
+
+class TelegramTask(BaseTask):
+    SUPPORTED_TASK_API_VERSION = 1
+    update_id = None
+    tbot = None
+
+    def initialize(self):
+        api_key = self.config.get('api_key')
+        if api_key == None:
+            self.emit_event(
+                'config_error',
+                formatted='api_key not defined.'
+            )
+            return
+        self.tbot = telegram.Bot(api_key)
+        try:
+            self.update_id = self.tbot.getUpdates()[0].update_id
+        except IndexError:
+            self.update_id = None
+
+    def work(self):
+        for update in self.tbot.getUpdates(offset=self.update_id, timeout=10):
+            self.update_id = update.update_id+1
+            if update.message:
+                if update.message.text == "/info":
+                    stats = self._get_player_stats()
+                    if stats:
+                        with self.bot.database as conn:
+                            cur = conn.cursor()
+                            cur.execute("SELECT DISTINCT COUNT(encounter_id) FROM catch_log WHERE dated >= datetime('now','-1 day')")
+                            catch_day = cur.fetchone()[0]
+                            cur.execute("SELECT DISTINCT COUNT(pokestop) FROM pokestop_log WHERE dated >= datetime('now','-1 day')")
+                            ps_day = cur.fetchone()[0]
+                            res = (
+                                "*"+self.bot.config.username+"*",
+                                "_Level:_ "+str(stats["level"]),
+                                "_XP:_ "+str(stats["experience"])+"/"+str(stats["next_level_xp"]),
+                                "_Pokemons Captured:_ "+str(stats["pokemons_captured"])+" ("+str(catch_day)+" _today_)",
+                                "_Poke Stop Visits:_ "+str(stats["poke_stop_visits"])+" ("+str(ps_day)+" _today_)",
+                                "_KM Walked:_ "+str(stats["km_walked"])
+                            )
+                            self.tbot.sendMessage(chat_id=update.message.chat_id, parse_mode='Markdown', text="\n".join(res))
+                            self.tbot.send_location(chat_id=update.message.chat_id, latitude=self.bot.api._position_lat, longitude=self.bot.api._position_lng)
+                    else:
+                        self.tbot.sendMessage(chat_id=update.message.chat_id, parse_mode='Markdown', text="Stats not loaded yet\n")
+                elif update.message.text == "/start" or update.message.text == "/help":
+                    res = (
+                        "Commands: ",
+                        "/info - info about bot"
+                    )
+                    self.tbot.sendMessage(chat_id=update.message.chat_id, parse_mode='Markdown', text="\n".join(res))
+
+    def _get_player_stats(self):
+        """
+        Helper method parsing the bot inventory object and returning the player stats object.
+        :return: The player stats object.
+        :rtype: dict
+        """
+        web_inventory = os.path.join(_base_dir, "web", "inventory-%s.json" % self.bot.config.username)
+        with open(web_inventory, "r") as infile:
+            json_inventory = json.load(infile)
+            infile.close()
+        return next((x["inventory_item_data"]["player_stats"]
+                     for x in json_inventory
+                     if x.get("inventory_item_data", {}).get("player_stats", {})),
+                    None)


Test patch: