We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
telegram_handler : TypeError: expected string or buffer
<!--

===============ISSUE SECTION===============

Before you create an Issue, please check the following:

1. Have you validated that your config.json is valid JSON? Use http://jsonlint.com/ to check.
2. Have you [searched our issue tracker](https://github.com/PokemonGoF/PokemonGo-Bot/issues?q=is%3Aissue+sort%3Aupdated-desc) to see if the issue already exists? If so, comment on that issue instead rather than creating a new issue.
3. Are you running on the `master` branch? We work on the `dev` branch and then add that functionality to `master` when it is stable. Your issue may be fixed on `dev` and there is no need for this issue, just wait and it will eventually be merged to `master`.
4. All Issue sections MUST be completed to help us determine the actual problem and find its cause
-->
### Expected Behavior

<!-- Tell us what you expect to happen -->

Bot to run and telegram to respond to /info request.
### Actual Behavior

<!-- Tell us what is happening -->

The telegram handler crashes
### Your FULL config.json (remove your username, password, gmapkey and any other private info)

<!-- Provide your FULL config file, feel free to use services such as pastebin.com to reduce clutter -->

  "type": "TelegramTask",
        "config": {
          "enabled": true,
          "master": null,
          "// old syntax, still supported: alert_catch": ["all"],
          "// new syntax:": {},
          "alert_catch": {
            "all": {"operator": "and", "cp": 1300, "iv": 0.95},
            "Snorlax": {"operator": "or", "cp": 900, "iv": 0.9}
### Output when issue occurred

<!-- Provide a reasonable sample from your output log (not just the error message), feel free to use services such as pastebin.com to reduce clutter -->

> Traceback (most recent call last):
>   File "/home/felis/PokemonGo-Bot/local/lib/python2.7/site-packages/eventlet/hubs/poll.py", line 115, in wait
>     listener.cb(fileno)
>   File "/home/felis/PokemonGo-Bot/local/lib/python2.7/site-packages/eventlet/green/thread.py", line 41, in __thread_body
>     func(_args, *_kwargs)
>   File "/home/felis/PokemonGo-Bot/pokemongo_bot/event_handlers/telegram_handler.py", line 82, in run
>     if not re.match(r'^[0-9]+$', self.master):
>   File "/home/felis/PokemonGo-Bot/lib/python2.7/re.py", line 141, in match
>     return _compile(pattern, flags).match(string)
> TypeError: expected string or buffer
> Removing descriptor: 16
### Steps to Reproduce

<!-- Tell us the steps you have taken to reproduce the issue -->

Unsure how it started. Now the error happens every startup since the bot is receiving a previous /info request.
master: null is on purpose. Multiple people are watching the same bot instance, so we don't need push notification.
### Other Information

OS: Ubuntu 16.04.1

<!-- Tell us what Operating system you're using --> 

Branch: dev

<!-- dev or master --> 

Git Commit: c270999a79d8e17f43e846249738b7b1f91936b8

<!-- run 'git log -n 1 --pretty=format:"%H"' --> 

Python Version: Python 2.7.12

<!-- run 'python -V' and paste it here) --> 

Any other relevant files/configs (eg: path files) 

<!-- Anything else which may be of relevance -->

<!-- ===============END OF ISSUE SECTION=============== -->

<!-- Note: Delete these lines and everything BELOW if creating an Issue -->

telegram_handler : TypeError: expected string or buffer
<!--

===============ISSUE SECTION===============

Before you create an Issue, please check the following:

1. Have you validated that your config.json is valid JSON? Use http://jsonlint.com/ to check.
2. Have you [searched our issue tracker](https://github.com/PokemonGoF/PokemonGo-Bot/issues?q=is%3Aissue+sort%3Aupdated-desc) to see if the issue already exists? If so, comment on that issue instead rather than creating a new issue.
3. Are you running on the `master` branch? We work on the `dev` branch and then add that functionality to `master` when it is stable. Your issue may be fixed on `dev` and there is no need for this issue, just wait and it will eventually be merged to `master`.
4. All Issue sections MUST be completed to help us determine the actual problem and find its cause
-->
### Expected Behavior

<!-- Tell us what you expect to happen -->

Bot to run and telegram to respond to /info request.
### Actual Behavior

<!-- Tell us what is happening -->

The telegram handler crashes
### Your FULL config.json (remove your username, password, gmapkey and any other private info)

<!-- Provide your FULL config file, feel free to use services such as pastebin.com to reduce clutter -->

  "type": "TelegramTask",
        "config": {
          "enabled": true,
          "master": null,
          "// old syntax, still supported: alert_catch": ["all"],
          "// new syntax:": {},
          "alert_catch": {
            "all": {"operator": "and", "cp": 1300, "iv": 0.95},
            "Snorlax": {"operator": "or", "cp": 900, "iv": 0.9}
### Output when issue occurred

<!-- Provide a reasonable sample from your output log (not just the error message), feel free to use services such as pastebin.com to reduce clutter -->

> Traceback (most recent call last):
>   File "/home/felis/PokemonGo-Bot/local/lib/python2.7/site-packages/eventlet/hubs/poll.py", line 115, in wait
>     listener.cb(fileno)
>   File "/home/felis/PokemonGo-Bot/local/lib/python2.7/site-packages/eventlet/green/thread.py", line 41, in __thread_body
>     func(_args, *_kwargs)
>   File "/home/felis/PokemonGo-Bot/pokemongo_bot/event_handlers/telegram_handler.py", line 82, in run
>     if not re.match(r'^[0-9]+$', self.master):
>   File "/home/felis/PokemonGo-Bot/lib/python2.7/re.py", line 141, in match
>     return _compile(pattern, flags).match(string)
> TypeError: expected string or buffer
> Removing descriptor: 16
### Steps to Reproduce

<!-- Tell us the steps you have taken to reproduce the issue -->

Unsure how it started. Now the error happens every startup since the bot is receiving a previous /info request.
master: null is on purpose. Multiple people are watching the same bot instance, so we don't need push notification.
### Other Information

OS: Ubuntu 16.04.1

<!-- Tell us what Operating system you're using --> 

Branch: dev

<!-- dev or master --> 

Git Commit: c270999a79d8e17f43e846249738b7b1f91936b8

<!-- run 'git log -n 1 --pretty=format:"%H"' --> 

Python Version: Python 2.7.12

<!-- run 'python -V' and paste it here) --> 

Any other relevant files/configs (eg: path files) 

<!-- Anything else which may be of relevance -->

<!-- ===============END OF ISSUE SECTION=============== -->

<!-- Note: Delete these lines and everything BELOW if creating an Issue -->


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pokemongo_bot/event_handlers/telegram_handler.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 from pokemongo_bot.event_manager import EventHandler
3 from pokemongo_bot.base_dir import _base_dir
4 import json
5 import os
6 import time
7 import telegram
8 import thread
9 import re
10 
11 DEBUG_ON = False
12 
13 class FileIOException(Exception):
14     pass
15 
16 class TelegramClass:
17 
18     update_id = None
19 
20     def __init__(self, bot, master, pokemons, config):
21         self.bot = bot
22         self.master = master
23         self.pokemons = pokemons
24         self._tbot = None
25         self.config = config
26 
27     def sendMessage(self, chat_id=None, parse_mode='Markdown', text=None):
28         self._tbot.sendMessage(chat_id=chat_id, parse_mode=parse_mode, text=text)
29 
30     def connect(self):
31         self._tbot = telegram.Bot(self.bot.config.telegram_token)
32         try:
33             self.update_id = self._tbot.getUpdates()[0].update_id
34         except IndexError:
35             self.update_id = None
36 
37     def _get_player_stats(self):
38         web_inventory = os.path.join(_base_dir, "web", "inventory-%s.json" % self.bot.config.username)
39         try:
40             with open(web_inventory, "r") as infile:
41                 json_inventory = json.load(infile)
42         except ValueError as exception:
43             self.bot.logger.info('[x] Error while opening inventory file for read: %s' % exception)
44             json_inventory = []
45         except:
46             raise FileIOException("Unexpected error reading from {}".format(web_inventory))
47         return next((x["inventory_item_data"]["player_stats"]
48                      for x in json_inventory
49                      if x.get("inventory_item_data", {}).get("player_stats", {})),
50                     None)
51     def send_player_stats_to_chat(self, chat_id):
52         stats = self._get_player_stats()
53         if stats:
54             with self.bot.database as conn:
55                 cur = conn.cursor()
56                 cur.execute("SELECT DISTINCT COUNT(encounter_id) FROM catch_log WHERE dated >= datetime('now','-1 day')")
57                 catch_day = cur.fetchone()[0]
58                 cur.execute("SELECT DISTINCT COUNT(pokestop) FROM pokestop_log WHERE dated >= datetime('now','-1 day')")
59                 ps_day = cur.fetchone()[0]
60                 res = (
61                     "*"+self.bot.config.username+"*",
62                     "_Level:_ "+str(stats["level"]),
63                     "_XP:_ "+str(stats["experience"])+"/"+str(stats["next_level_xp"]),
64                     "_Pokemons Captured:_ "+str(stats["pokemons_captured"])+" ("+str(catch_day)+" _last 24h_)",
65                     "_Poke Stop Visits:_ "+str(stats["poke_stop_visits"])+" ("+str(ps_day)+" _last 24h_)",
66                     "_KM Walked:_ "+str("%.2f" % stats["km_walked"])
67                 )
68             self._tbot.sendMessage(chat_id=chat_id, parse_mode='Markdown', text="\n".join(res))
69             self._tbot.send_location(chat_id=chat_id, latitude=self.bot.api._position_lat, longitude=self.bot.api._position_lng)
70         else:
71             self._tbot.sendMessage(chat_id=chat_id, parse_mode='Markdown', text="Stats not loaded yet\n")
72     def run(self):
73         time.sleep(1)
74         while True:
75             try:
76                 for update in self._tbot.getUpdates(offset=self.update_id, timeout=10):
77                     self.update_id = update.update_id+1
78                     if update.message:
79                         self.bot.logger.info("message from {} ({}): {}".format(update.message.from_user.username, update.message.from_user.id, update.message.text))
80                         if self.master and self.master not in [update.message.from_user.id, "@{}".format(update.message.from_user.username)]:
81                             continue
82                         if not re.match(r'^[0-9]+$', self.master):
83                             # the "master" is not numeric, set self.master to update.message.chat_id and re-instantiate the handler
84                             newconfig = self.config
85                             newconfig['master'] = update.message.chat_id
86                             # remove old handler
87                             self.bot.event_manager._handlers = filter(lambda x: not isinstance(x, TelegramHandler), self.bot.event_manager._handlers)
88                             # add new handler (passing newconfig as parameter)
89                             self.bot.event_manager.add_handler(TelegramHandler(self.bot, newconfig))
90                         if update.message.text == "/info":
91                             self.send_player_stats_to_chat(update.message.chat_id)
92                         elif update.message.text == "/start" or update.message.text == "/help":
93                             res = (
94                                 "Commands: ",
95                                 "/info - info about bot"
96                             )
97                             self._tbot.sendMessage(chat_id=update.message.chat_id, parse_mode='Markdown', text="\n".join(res))
98             except telegram.error.NetworkError:
99                 time.sleep(1)
100             except telegram.error.TelegramError:
101                 time.sleep(10)
102             except telegram.error.Unauthorized:
103                 self.update_id += 1
104 
105 class TelegramHandler(EventHandler):
106     def __init__(self, bot, config):
107         self.bot = bot
108         self.tbot = None
109         self.master = config.get('master', None)
110         self.pokemons = config.get('alert_catch', {})
111         self.whoami = "TelegramHandler"
112         self.config = config
113 
114     def handle_event(self, event, sender, level, formatted_msg, data):
115         if self.tbot is None:
116             try:
117                 self.tbot = TelegramClass(self.bot, self.master, self.pokemons, self.config)
118                 self.tbot.connect()
119                 thread.start_new_thread(self.tbot.run)
120             except Exception as inst:
121                 self.tbot = None
122         if self.master:
123             if not re.match(r'^[0-9]+$', str(self.master)):
124                 return
125             master = self.master
126 
127             if event == 'level_up':
128                 msg = "level up ({})".format(data["current_level"])
129             elif event == 'pokemon_caught':
130                 if isinstance(self.pokemons, list):
131                     if data["pokemon"] in self.pokemons or "all" in self.pokemons:
132                         msg = "Caught {} CP: {}, IV: {}".format(data["pokemon"], data["cp"], data["iv"])
133                     else:
134                         return
135                 else:
136                     if data["pokemon"] in self.pokemons:
137                         trigger = self.pokemons[data["pokemon"]]
138                     elif "all" in self.pokemons:
139                         trigger = self.pokemons["all"]
140                     else:
141                         return
142                     if (not "operator" in trigger or trigger["operator"] == "and") and data["cp"] >= trigger["cp"] and data["iv"] >= trigger["iv"] or ("operator" in trigger and trigger["operator"] == "or" and (data["cp"] >= trigger["cp"] or data["iv"] >= trigger["iv"])):
143                         msg = "Caught {} CP: {}, IV: {}".format(data["pokemon"], data["cp"], data["iv"])
144                     else:
145                         return
146             elif event == 'egg_hatched':
147                 msg = "Egg hatched with a {} CP: {}, IV: {}".format(data["pokemon"], data["cp"], data["iv"])
148             elif event == 'catch_limit':
149                 self.tbot.send_player_stats_to_chat(master)
150                 msg = "*You have reached your daily catch limit, quitting.*"
151             else:
152                 return
153             self.tbot.sendMessage(chat_id=master, parse_mode='Markdown', text=msg)
154
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/pokemongo_bot/event_handlers/telegram_handler.py b/pokemongo_bot/event_handlers/telegram_handler.py
--- a/pokemongo_bot/event_handlers/telegram_handler.py
+++ b/pokemongo_bot/event_handlers/telegram_handler.py
@@ -79,7 +79,7 @@
                         self.bot.logger.info("message from {} ({}): {}".format(update.message.from_user.username, update.message.from_user.id, update.message.text))
                         if self.master and self.master not in [update.message.from_user.id, "@{}".format(update.message.from_user.username)]:
                             continue
-                        if not re.match(r'^[0-9]+$', self.master):
+                        if self.master and not re.match(r'^[0-9]+$', str(self.master)):
                             # the "master" is not numeric, set self.master to update.message.chat_id and re-instantiate the handler
                             newconfig = self.config
                             newconfig['master'] = update.message.chat_id

{"golden_diff": "diff --git a/pokemongo_bot/event_handlers/telegram_handler.py b/pokemongo_bot/event_handlers/telegram_handler.py\n--- a/pokemongo_bot/event_handlers/telegram_handler.py\n+++ b/pokemongo_bot/event_handlers/telegram_handler.py\n@@ -79,7 +79,7 @@\n                         self.bot.logger.info(\"message from {} ({}): {}\".format(update.message.from_user.username, update.message.from_user.id, update.message.text))\n                         if self.master and self.master not in [update.message.from_user.id, \"@{}\".format(update.message.from_user.username)]:\n                             continue\n-                        if not re.match(r'^[0-9]+$', self.master):\n+                        if self.master and not re.match(r'^[0-9]+$', str(self.master)):\n                             # the \"master\" is not numeric, set self.master to update.message.chat_id and re-instantiate the handler\n                             newconfig = self.config\n                             newconfig['master'] = update.message.chat_id\n", "issue": "telegram_handler : TypeError: expected string or buffer\n<!--\n\n===============ISSUE SECTION===============\n\nBefore you create an Issue, please check the following:\n\n1. Have you validated that your config.json is valid JSON? Use http://jsonlint.com/ to check.\n2. Have you [searched our issue tracker](https://github.com/PokemonGoF/PokemonGo-Bot/issues?q=is%3Aissue+sort%3Aupdated-desc) to see if the issue already exists? If so, comment on that issue instead rather than creating a new issue.\n3. Are you running on the `master` branch? We work on the `dev` branch and then add that functionality to `master` when it is stable. Your issue may be fixed on `dev` and there is no need for this issue, just wait and it will eventually be merged to `master`.\n4. All Issue sections MUST be completed to help us determine the actual problem and find its cause\n-->\n### Expected Behavior\n\n<!-- Tell us what you expect to happen -->\n\nBot to run and telegram to respond to /info request.\n### Actual Behavior\n\n<!-- Tell us what is happening -->\n\nThe telegram handler crashes\n### Your FULL config.json (remove your username, password, gmapkey and any other private info)\n\n<!-- Provide your FULL config file, feel free to use services such as pastebin.com to reduce clutter -->\n\n  \"type\": \"TelegramTask\",\n        \"config\": {\n          \"enabled\": true,\n          \"master\": null,\n          \"// old syntax, still supported: alert_catch\": [\"all\"],\n          \"// new syntax:\": {},\n          \"alert_catch\": {\n            \"all\": {\"operator\": \"and\", \"cp\": 1300, \"iv\": 0.95},\n            \"Snorlax\": {\"operator\": \"or\", \"cp\": 900, \"iv\": 0.9}\n### Output when issue occurred\n\n<!-- Provide a reasonable sample from your output log (not just the error message), feel free to use services such as pastebin.com to reduce clutter -->\n\n> Traceback (most recent call last):\n>   File \"/home/felis/PokemonGo-Bot/local/lib/python2.7/site-packages/eventlet/hubs/poll.py\", line 115, in wait\n>     listener.cb(fileno)\n>   File \"/home/felis/PokemonGo-Bot/local/lib/python2.7/site-packages/eventlet/green/thread.py\", line 41, in __thread_body\n>     func(_args, *_kwargs)\n>   File \"/home/felis/PokemonGo-Bot/pokemongo_bot/event_handlers/telegram_handler.py\", line 82, in run\n>     if not re.match(r'^[0-9]+$', self.master):\n>   File \"/home/felis/PokemonGo-Bot/lib/python2.7/re.py\", line 141, in match\n>     return _compile(pattern, flags).match(string)\n> TypeError: expected string or buffer\n> Removing descriptor: 16\n### Steps to Reproduce\n\n<!-- Tell us the steps you have taken to reproduce the issue -->\n\nUnsure how it started. Now the error happens every startup since the bot is receiving a previous /info request.\nmaster: null is on purpose. Multiple people are watching the same bot instance, so we don't need push notification.\n### Other Information\n\nOS: Ubuntu 16.04.1\n\n<!-- Tell us what Operating system you're using --> \n\nBranch: dev\n\n<!-- dev or master --> \n\nGit Commit: c270999a79d8e17f43e846249738b7b1f91936b8\n\n<!-- run 'git log -n 1 --pretty=format:\"%H\"' --> \n\nPython Version: Python 2.7.12\n\n<!-- run 'python -V' and paste it here) --> \n\nAny other relevant files/configs (eg: path files) \n\n<!-- Anything else which may be of relevance -->\n\n<!-- ===============END OF ISSUE SECTION=============== -->\n\n<!-- Note: Delete these lines and everything BELOW if creating an Issue -->\n\ntelegram_handler : TypeError: expected string or buffer\n<!--\n\n===============ISSUE SECTION===============\n\nBefore you create an Issue, please check the following:\n\n1. Have you validated that your config.json is valid JSON? Use http://jsonlint.com/ to check.\n2. Have you [searched our issue tracker](https://github.com/PokemonGoF/PokemonGo-Bot/issues?q=is%3Aissue+sort%3Aupdated-desc) to see if the issue already exists? If so, comment on that issue instead rather than creating a new issue.\n3. Are you running on the `master` branch? We work on the `dev` branch and then add that functionality to `master` when it is stable. Your issue may be fixed on `dev` and there is no need for this issue, just wait and it will eventually be merged to `master`.\n4. All Issue sections MUST be completed to help us determine the actual problem and find its cause\n-->\n### Expected Behavior\n\n<!-- Tell us what you expect to happen -->\n\nBot to run and telegram to respond to /info request.\n### Actual Behavior\n\n<!-- Tell us what is happening -->\n\nThe telegram handler crashes\n### Your FULL config.json (remove your username, password, gmapkey and any other private info)\n\n<!-- Provide your FULL config file, feel free to use services such as pastebin.com to reduce clutter -->\n\n  \"type\": \"TelegramTask\",\n        \"config\": {\n          \"enabled\": true,\n          \"master\": null,\n          \"// old syntax, still supported: alert_catch\": [\"all\"],\n          \"// new syntax:\": {},\n          \"alert_catch\": {\n            \"all\": {\"operator\": \"and\", \"cp\": 1300, \"iv\": 0.95},\n            \"Snorlax\": {\"operator\": \"or\", \"cp\": 900, \"iv\": 0.9}\n### Output when issue occurred\n\n<!-- Provide a reasonable sample from your output log (not just the error message), feel free to use services such as pastebin.com to reduce clutter -->\n\n> Traceback (most recent call last):\n>   File \"/home/felis/PokemonGo-Bot/local/lib/python2.7/site-packages/eventlet/hubs/poll.py\", line 115, in wait\n>     listener.cb(fileno)\n>   File \"/home/felis/PokemonGo-Bot/local/lib/python2.7/site-packages/eventlet/green/thread.py\", line 41, in __thread_body\n>     func(_args, *_kwargs)\n>   File \"/home/felis/PokemonGo-Bot/pokemongo_bot/event_handlers/telegram_handler.py\", line 82, in run\n>     if not re.match(r'^[0-9]+$', self.master):\n>   File \"/home/felis/PokemonGo-Bot/lib/python2.7/re.py\", line 141, in match\n>     return _compile(pattern, flags).match(string)\n> TypeError: expected string or buffer\n> Removing descriptor: 16\n### Steps to Reproduce\n\n<!-- Tell us the steps you have taken to reproduce the issue -->\n\nUnsure how it started. Now the error happens every startup since the bot is receiving a previous /info request.\nmaster: null is on purpose. Multiple people are watching the same bot instance, so we don't need push notification.\n### Other Information\n\nOS: Ubuntu 16.04.1\n\n<!-- Tell us what Operating system you're using --> \n\nBranch: dev\n\n<!-- dev or master --> \n\nGit Commit: c270999a79d8e17f43e846249738b7b1f91936b8\n\n<!-- run 'git log -n 1 --pretty=format:\"%H\"' --> \n\nPython Version: Python 2.7.12\n\n<!-- run 'python -V' and paste it here) --> \n\nAny other relevant files/configs (eg: path files) \n\n<!-- Anything else which may be of relevance -->\n\n<!-- ===============END OF ISSUE SECTION=============== -->\n\n<!-- Note: Delete these lines and everything BELOW if creating an Issue -->\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\nfrom pokemongo_bot.event_manager import EventHandler\nfrom pokemongo_bot.base_dir import _base_dir\nimport json\nimport os\nimport time\nimport telegram\nimport thread\nimport re\n\nDEBUG_ON = False\n\nclass FileIOException(Exception):\n    pass\n\nclass TelegramClass:\n\n    update_id = None\n\n    def __init__(self, bot, master, pokemons, config):\n        self.bot = bot\n        self.master = master\n        self.pokemons = pokemons\n        self._tbot = None\n        self.config = config\n\n    def sendMessage(self, chat_id=None, parse_mode='Markdown', text=None):\n        self._tbot.sendMessage(chat_id=chat_id, parse_mode=parse_mode, text=text)\n\n    def connect(self):\n        self._tbot = telegram.Bot(self.bot.config.telegram_token)\n        try:\n            self.update_id = self._tbot.getUpdates()[0].update_id\n        except IndexError:\n            self.update_id = None\n\n    def _get_player_stats(self):\n        web_inventory = os.path.join(_base_dir, \"web\", \"inventory-%s.json\" % self.bot.config.username)\n        try:\n            with open(web_inventory, \"r\") as infile:\n                json_inventory = json.load(infile)\n        except ValueError as exception:\n            self.bot.logger.info('[x] Error while opening inventory file for read: %s' % exception)\n            json_inventory = []\n        except:\n            raise FileIOException(\"Unexpected error reading from {}\".format(web_inventory))\n        return next((x[\"inventory_item_data\"][\"player_stats\"]\n                     for x in json_inventory\n                     if x.get(\"inventory_item_data\", {}).get(\"player_stats\", {})),\n                    None)\n    def send_player_stats_to_chat(self, chat_id):\n        stats = self._get_player_stats()\n        if stats:\n            with self.bot.database as conn:\n                cur = conn.cursor()\n                cur.execute(\"SELECT DISTINCT COUNT(encounter_id) FROM catch_log WHERE dated >= datetime('now','-1 day')\")\n                catch_day = cur.fetchone()[0]\n                cur.execute(\"SELECT DISTINCT COUNT(pokestop) FROM pokestop_log WHERE dated >= datetime('now','-1 day')\")\n                ps_day = cur.fetchone()[0]\n                res = (\n                    \"*\"+self.bot.config.username+\"*\",\n                    \"_Level:_ \"+str(stats[\"level\"]),\n                    \"_XP:_ \"+str(stats[\"experience\"])+\"/\"+str(stats[\"next_level_xp\"]),\n                    \"_Pokemons Captured:_ \"+str(stats[\"pokemons_captured\"])+\" (\"+str(catch_day)+\" _last 24h_)\",\n                    \"_Poke Stop Visits:_ \"+str(stats[\"poke_stop_visits\"])+\" (\"+str(ps_day)+\" _last 24h_)\",\n                    \"_KM Walked:_ \"+str(\"%.2f\" % stats[\"km_walked\"])\n                )\n            self._tbot.sendMessage(chat_id=chat_id, parse_mode='Markdown', text=\"\\n\".join(res))\n            self._tbot.send_location(chat_id=chat_id, latitude=self.bot.api._position_lat, longitude=self.bot.api._position_lng)\n        else:\n            self._tbot.sendMessage(chat_id=chat_id, parse_mode='Markdown', text=\"Stats not loaded yet\\n\")\n    def run(self):\n        time.sleep(1)\n        while True:\n            try:\n                for update in self._tbot.getUpdates(offset=self.update_id, timeout=10):\n                    self.update_id = update.update_id+1\n                    if update.message:\n                        self.bot.logger.info(\"message from {} ({}): {}\".format(update.message.from_user.username, update.message.from_user.id, update.message.text))\n                        if self.master and self.master not in [update.message.from_user.id, \"@{}\".format(update.message.from_user.username)]:\n                            continue\n                        if not re.match(r'^[0-9]+$', self.master):\n                            # the \"master\" is not numeric, set self.master to update.message.chat_id and re-instantiate the handler\n                            newconfig = self.config\n                            newconfig['master'] = update.message.chat_id\n                            # remove old handler\n                            self.bot.event_manager._handlers = filter(lambda x: not isinstance(x, TelegramHandler), self.bot.event_manager._handlers)\n                            # add new handler (passing newconfig as parameter)\n                            self.bot.event_manager.add_handler(TelegramHandler(self.bot, newconfig))\n                        if update.message.text == \"/info\":\n                            self.send_player_stats_to_chat(update.message.chat_id)\n                        elif update.message.text == \"/start\" or update.message.text == \"/help\":\n                            res = (\n                                \"Commands: \",\n                                \"/info - info about bot\"\n                            )\n                            self._tbot.sendMessage(chat_id=update.message.chat_id, parse_mode='Markdown', text=\"\\n\".join(res))\n            except telegram.error.NetworkError:\n                time.sleep(1)\n            except telegram.error.TelegramError:\n                time.sleep(10)\n            except telegram.error.Unauthorized:\n                self.update_id += 1\n\nclass TelegramHandler(EventHandler):\n    def __init__(self, bot, config):\n        self.bot = bot\n        self.tbot = None\n        self.master = config.get('master', None)\n        self.pokemons = config.get('alert_catch', {})\n        self.whoami = \"TelegramHandler\"\n        self.config = config\n\n    def handle_event(self, event, sender, level, formatted_msg, data):\n        if self.tbot is None:\n            try:\n                self.tbot = TelegramClass(self.bot, self.master, self.pokemons, self.config)\n                self.tbot.connect()\n                thread.start_new_thread(self.tbot.run)\n            except Exception as inst:\n                self.tbot = None\n        if self.master:\n            if not re.match(r'^[0-9]+$', str(self.master)):\n                return\n            master = self.master\n\n            if event == 'level_up':\n                msg = \"level up ({})\".format(data[\"current_level\"])\n            elif event == 'pokemon_caught':\n                if isinstance(self.pokemons, list):\n                    if data[\"pokemon\"] in self.pokemons or \"all\" in self.pokemons:\n                        msg = \"Caught {} CP: {}, IV: {}\".format(data[\"pokemon\"], data[\"cp\"], data[\"iv\"])\n                    else:\n                        return\n                else:\n                    if data[\"pokemon\"] in self.pokemons:\n                        trigger = self.pokemons[data[\"pokemon\"]]\n                    elif \"all\" in self.pokemons:\n                        trigger = self.pokemons[\"all\"]\n                    else:\n                        return\n                    if (not \"operator\" in trigger or trigger[\"operator\"] == \"and\") and data[\"cp\"] >= trigger[\"cp\"] and data[\"iv\"] >= trigger[\"iv\"] or (\"operator\" in trigger and trigger[\"operator\"] == \"or\" and (data[\"cp\"] >= trigger[\"cp\"] or data[\"iv\"] >= trigger[\"iv\"])):\n                        msg = \"Caught {} CP: {}, IV: {}\".format(data[\"pokemon\"], data[\"cp\"], data[\"iv\"])\n                    else:\n                        return\n            elif event == 'egg_hatched':\n                msg = \"Egg hatched with a {} CP: {}, IV: {}\".format(data[\"pokemon\"], data[\"cp\"], data[\"iv\"])\n            elif event == 'catch_limit':\n                self.tbot.send_player_stats_to_chat(master)\n                msg = \"*You have reached your daily catch limit, quitting.*\"\n            else:\n                return\n            self.tbot.sendMessage(chat_id=master, parse_mode='Markdown', text=msg)\n", "path": "pokemongo_bot/event_handlers/telegram_handler.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\nfrom pokemongo_bot.event_manager import EventHandler\nfrom pokemongo_bot.base_dir import _base_dir\nimport json\nimport os\nimport time\nimport telegram\nimport thread\nimport re\n\nDEBUG_ON = False\n\nclass FileIOException(Exception):\n    pass\n\nclass TelegramClass:\n\n    update_id = None\n\n    def __init__(self, bot, master, pokemons, config):\n        self.bot = bot\n        self.master = master\n        self.pokemons = pokemons\n        self._tbot = None\n        self.config = config\n\n    def sendMessage(self, chat_id=None, parse_mode='Markdown', text=None):\n        self._tbot.sendMessage(chat_id=chat_id, parse_mode=parse_mode, text=text)\n\n    def connect(self):\n        self._tbot = telegram.Bot(self.bot.config.telegram_token)\n        try:\n            self.update_id = self._tbot.getUpdates()[0].update_id\n        except IndexError:\n            self.update_id = None\n\n    def _get_player_stats(self):\n        web_inventory = os.path.join(_base_dir, \"web\", \"inventory-%s.json\" % self.bot.config.username)\n        try:\n            with open(web_inventory, \"r\") as infile:\n                json_inventory = json.load(infile)\n        except ValueError as exception:\n            self.bot.logger.info('[x] Error while opening inventory file for read: %s' % exception)\n            json_inventory = []\n        except:\n            raise FileIOException(\"Unexpected error reading from {}\".format(web_inventory))\n        return next((x[\"inventory_item_data\"][\"player_stats\"]\n                     for x in json_inventory\n                     if x.get(\"inventory_item_data\", {}).get(\"player_stats\", {})),\n                    None)\n    def send_player_stats_to_chat(self, chat_id):\n        stats = self._get_player_stats()\n        if stats:\n            with self.bot.database as conn:\n                cur = conn.cursor()\n                cur.execute(\"SELECT DISTINCT COUNT(encounter_id) FROM catch_log WHERE dated >= datetime('now','-1 day')\")\n                catch_day = cur.fetchone()[0]\n                cur.execute(\"SELECT DISTINCT COUNT(pokestop) FROM pokestop_log WHERE dated >= datetime('now','-1 day')\")\n                ps_day = cur.fetchone()[0]\n                res = (\n                    \"*\"+self.bot.config.username+\"*\",\n                    \"_Level:_ \"+str(stats[\"level\"]),\n                    \"_XP:_ \"+str(stats[\"experience\"])+\"/\"+str(stats[\"next_level_xp\"]),\n                    \"_Pokemons Captured:_ \"+str(stats[\"pokemons_captured\"])+\" (\"+str(catch_day)+\" _last 24h_)\",\n                    \"_Poke Stop Visits:_ \"+str(stats[\"poke_stop_visits\"])+\" (\"+str(ps_day)+\" _last 24h_)\",\n                    \"_KM Walked:_ \"+str(\"%.2f\" % stats[\"km_walked\"])\n                )\n            self._tbot.sendMessage(chat_id=chat_id, parse_mode='Markdown', text=\"\\n\".join(res))\n            self._tbot.send_location(chat_id=chat_id, latitude=self.bot.api._position_lat, longitude=self.bot.api._position_lng)\n        else:\n            self._tbot.sendMessage(chat_id=chat_id, parse_mode='Markdown', text=\"Stats not loaded yet\\n\")\n    def run(self):\n        time.sleep(1)\n        while True:\n            try:\n                for update in self._tbot.getUpdates(offset=self.update_id, timeout=10):\n                    self.update_id = update.update_id+1\n                    if update.message:\n                        self.bot.logger.info(\"message from {} ({}): {}\".format(update.message.from_user.username, update.message.from_user.id, update.message.text))\n                        if self.master and self.master not in [update.message.from_user.id, \"@{}\".format(update.message.from_user.username)]:\n                            continue\n                        if self.master and not re.match(r'^[0-9]+$', str(self.master)):\n                            # the \"master\" is not numeric, set self.master to update.message.chat_id and re-instantiate the handler\n                            newconfig = self.config\n                            newconfig['master'] = update.message.chat_id\n                            # remove old handler\n                            self.bot.event_manager._handlers = filter(lambda x: not isinstance(x, TelegramHandler), self.bot.event_manager._handlers)\n                            # add new handler (passing newconfig as parameter)\n                            self.bot.event_manager.add_handler(TelegramHandler(self.bot, newconfig))\n                        if update.message.text == \"/info\":\n                            self.send_player_stats_to_chat(update.message.chat_id)\n                        elif update.message.text == \"/start\" or update.message.text == \"/help\":\n                            res = (\n                                \"Commands: \",\n                                \"/info - info about bot\"\n                            )\n                            self._tbot.sendMessage(chat_id=update.message.chat_id, parse_mode='Markdown', text=\"\\n\".join(res))\n            except telegram.error.NetworkError:\n                time.sleep(1)\n            except telegram.error.TelegramError:\n                time.sleep(10)\n            except telegram.error.Unauthorized:\n                self.update_id += 1\n\nclass TelegramHandler(EventHandler):\n    def __init__(self, bot, config):\n        self.bot = bot\n        self.tbot = None\n        self.master = config.get('master', None)\n        self.pokemons = config.get('alert_catch', {})\n        self.whoami = \"TelegramHandler\"\n        self.config = config\n\n    def handle_event(self, event, sender, level, formatted_msg, data):\n        if self.tbot is None:\n            try:\n                self.tbot = TelegramClass(self.bot, self.master, self.pokemons, self.config)\n                self.tbot.connect()\n                thread.start_new_thread(self.tbot.run)\n            except Exception as inst:\n                self.tbot = None\n        if self.master:\n            if not re.match(r'^[0-9]+$', str(self.master)):\n                return\n            master = self.master\n\n            if event == 'level_up':\n                msg = \"level up ({})\".format(data[\"current_level\"])\n            elif event == 'pokemon_caught':\n                if isinstance(self.pokemons, list):\n                    if data[\"pokemon\"] in self.pokemons or \"all\" in self.pokemons:\n                        msg = \"Caught {} CP: {}, IV: {}\".format(data[\"pokemon\"], data[\"cp\"], data[\"iv\"])\n                    else:\n                        return\n                else:\n                    if data[\"pokemon\"] in self.pokemons:\n                        trigger = self.pokemons[data[\"pokemon\"]]\n                    elif \"all\" in self.pokemons:\n                        trigger = self.pokemons[\"all\"]\n                    else:\n                        return\n                    if (not \"operator\" in trigger or trigger[\"operator\"] == \"and\") and data[\"cp\"] >= trigger[\"cp\"] and data[\"iv\"] >= trigger[\"iv\"] or (\"operator\" in trigger and trigger[\"operator\"] == \"or\" and (data[\"cp\"] >= trigger[\"cp\"] or data[\"iv\"] >= trigger[\"iv\"])):\n                        msg = \"Caught {} CP: {}, IV: {}\".format(data[\"pokemon\"], data[\"cp\"], data[\"iv\"])\n                    else:\n                        return\n            elif event == 'egg_hatched':\n                msg = \"Egg hatched with a {} CP: {}, IV: {}\".format(data[\"pokemon\"], data[\"cp\"], data[\"iv\"])\n            elif event == 'catch_limit':\n                self.tbot.send_player_stats_to_chat(master)\n                msg = \"*You have reached your daily catch limit, quitting.*\"\n            else:\n                return\n            self.tbot.sendMessage(chat_id=master, parse_mode='Markdown', text=msg)\n", "path": "pokemongo_bot/event_handlers/telegram_handler.py"}]}