Repository: Flexget/Flexget

Issue:
Telegram notify to gorup giving error regarding supergroup
### Expected behaviour:

When I have a completed task I have a  notify to telegram, this was working ok, and sends all completed task a notify to telegram

### Actual behaviour:

But now (I don't know if result of some changes I made to my group, or some changes to telegram), my telegram message to the groups are returning a error regarding supergroup.


### Steps to reproduce:

I don't know who to create a supergroup, but I think it might be related with the fact that I changed my admin rights to send anonymous messages.

- Try create a group
- Add the bot
- Change the admin rights from one user to send anonymous messages
- I reverted it back to disable that, but no changes  

#### Config:
```yaml

  test_telegram:
    notify:
      entries:
        what: accepted
        title: |+
          Test
        message: |+
          Test
        via:
          - telegram:
              bot_token: '{? telegram.token ?}'
              parse_mode: markdown
              recipients:
                - group: '{? telegram.group ?}'
    disable:
      - seen
      - seen_info_hash
      - retry_failed
    accept_all: yes
    limit:
      amount: 1
      from:
        filesystem:
          path: '{? system.root.server.path ?}/'
          recursive: no
          retrieve: dirs

```
  
#### Log:
<details>
 <summary>(click to expand)</summary>

```
2020-11-03 10:01:51 DEBUG    notify        test_telegram   Sending a notification to `telegram`
2020-11-03 10:01:51 DEBUG    telegram      test_telegram   token=xxxxxxxxxxxxxxxxxxxxxxxxx, parse_mode=markdown, disable_previews=False, usernames=[], fullnames=[], groups=['xxxxxxxxxxx']
2020-11-03 10:01:52 DEBUG    telegram      test_telegram   loading cached chat ids
2020-11-03 10:01:52 DEBUG    telegram      test_telegram   found 1 cached chat_ids: ['id=-111111111 group=xxxxxxxxxxx']
2020-11-03 10:01:52 DEBUG    telegram      test_telegram   all chat ids found in cache
2020-11-03 10:01:52 DEBUG    telegram      test_telegram   chat_ids=[<flexget.components.notify.notifiers.telegram.ChatIdEntry object at 0x7f0db2e0cbe0>]
2020-11-03 10:01:52 DEBUG    telegram      test_telegram   sending msg to telegram servers: Teste
2020-11-03 10:01:52 WARNING  telegram      test_telegram   Failed to render message using parse mode Markdown. Falling back to basic parsing: Group migrated to supergroup. New chat id: -2222222222222
2020-11-03 10:01:52 WARNING  notify        test_telegram   Error while sending notification to `telegram`: Group migrated to supergroup. New chat id: -2222222222222
2020-11-03 10:01:52 DEBUG    util.simple_persistence test_telegram   Flushing simple persistence for task test_telegram to db.
2020-11-03 10:01:52 DEBUG    util.simple_persistence test_telegram   Flushing simple persistence for task None to db.
```
</details>

### Additional information:

- FlexGet version: 3.1.82
- Python version: 3.7.3
- Installation method: VENV
- Using daemon (yes/no): yes
- OS and version: Debian 10



Discussion:
Ok I can confirm that changing the admin to "Remain Anonymous" messages changes the group to SuperGroup and does not allow to rever it back again... to do this do

- Go To "Manage Group" in group settings
- Click Administrators
- Click the User/Admin Username
- Toggle Remain Anonymous
- Run Flexget task to send message
A new test, log without changing the group permissions:

```
2020-11-03 10:55:40 DEBUG    telegram      test_telegram   token=xxxxxxxxxxxxxxxxxxxxxx, parse_mode=markdown, disable_previews=False, usernames=[], fullnames=[], groups=['MyTeste1']
2020-11-03 10:55:40 DEBUG    telegram.bot  test_telegram   Entering: get_me
2020-11-03 10:55:40 DEBUG    telegram.vendor.ptb_urllib3.urllib3.connectionpool test_telegram   Starting new HTTPS connection (1): api.telegram.org
2020-11-03 10:55:40 DEBUG    telegram.vendor.ptb_urllib3.urllib3.connectionpool test_telegram   https://api.telegram.org:443 "GET /botxxxxxxxxxxxxxxxxxxxxxx/getMe HTTP/1.1" 200 200
2020-11-03 10:55:40 DEBUG    telegram.bot  test_telegram   {'id': xxxxxxxxxx, 'first_name': 'Bot', 'is_bot': True, 'username': 'Bot'}
2020-11-03 10:55:40 DEBUG    telegram.bot  test_telegram   Exiting: get_me
2020-11-03 10:55:40 DEBUG    telegram      test_telegram   loading cached chat ids
2020-11-03 10:55:40 DEBUG    telegram      test_telegram   found 0 cached chat_ids: []
2020-11-03 10:55:40 DEBUG    telegram      test_telegram   loading new chat ids
2020-11-03 10:55:40 DEBUG    telegram.bot  test_telegram   Entering: get_updates
2020-11-03 10:55:40 DEBUG    telegram.vendor.ptb_urllib3.urllib3.connectionpool test_telegram   https://api.telegram.org:443 "POST /botxxxxxxxxxxxxxxxxxxxxxx/getUpdates HTTP/1.1" 200 2918
2020-11-03 10:55:40 DEBUG    telegram.bot  test_telegram   Getting updates: [xxxxx, xxxxx, xxxxx, xxxxx, xxxxx, 363791785, xxxxx, xxxxx, xxxxx]
2020-11-03 10:55:40 DEBUG    telegram.bot  test_telegram   [<telegram.update.Update object at 0x7fb49dacfe48>, <telegram.update.Update object at 0x7fb49dacfef0>, <telegram.update.Update object at 0x7fb49dad3518>, <telegram.update.Update object at 0x7fb49dad30b8>, <telegram.update.Update object at 0x7fb49dad3358>, <telegram.update.Update object at 0x7fb49dad3198>, <telegram.update.Update object at 0x7fb49dad3a20>, <telegram.update.Update object at 0x7fb49dad34a8>, <telegram.update.Update object at 0x7fb49dad7ba8>]
2020-11-03 10:55:40 DEBUG    telegram.bot  test_telegram   Exiting: get_updates
2020-11-03 10:55:40 DEBUG    telegram      test_telegram   found 1 new chat_ids: ['id=xxxxxxx group=MyTeste1']
2020-11-03 10:55:40 DEBUG    telegram      test_telegram   chat_ids=[<flexget.components.notify.notifiers.telegram.ChatIdEntry object at 0x7fb49db21d30>]
2020-11-03 10:55:40 INFO     telegram      test_telegram   saving updated chat_ids to db
2020-11-03 10:55:40 DEBUG    telegram      test_telegram   sending msg to telegram servers: Teste
2020-11-03 10:55:40 DEBUG    telegram.bot  test_telegram   Entering: send_message
2020-11-03 10:55:40 DEBUG    telegram.vendor.ptb_urllib3.urllib3.connectionpool test_telegram   https://api.telegram.org:443 "POST /botxxxxxxxxxxxxxxxxxxxxxx/sendMessage HTTP/1.1" 200 267
2020-11-03 10:55:40 DEBUG    telegram.bot  test_telegram   {'message_id': 3967, 'date': 1604400940, 'chat': {'id': xxxxxxx, 'type': 'group', 'title': 'MyTeste1', 'all_members_are_administrators': True}, 'text': 'Teste', 'entities': [], 'caption_entities': [], 'photo': [], 'new_chat_members': [], 'new_chat_photo': [], 'delete_chat_photo': False, 'group_chat_created': False, 'supergroup_chat_created': False, 'channel_chat_created': False, 'from': {'id': xxxxxxxxxx, 'first_name': 'Bot', 'is_bot': True, 'username': 'Bot'}}
2020-11-03 10:55:40 DEBUG    telegram.bot  test_telegram   Exiting: send_message
2020-11-03 10:55:40 VERBOSE  notify        test_telegram   Successfully sent a notification to `telegram`
```
Now I changed the permissions

```
2020-11-03 11:01:30 DEBUG    telegram      test_telegram   token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, parse_mode=markdown, disable_previews=False, usernames=[], fullnames=[], groups=['MyTeste1']
2020-11-03 11:01:30 DEBUG    telegram.bot  test_telegram   Entering: get_me
2020-11-03 11:01:30 DEBUG    telegram.vendor.ptb_urllib3.urllib3.connectionpool test_telegram   Starting new HTTPS connection (1): api.telegram.org
2020-11-03 11:01:30 DEBUG    telegram.vendor.ptb_urllib3.urllib3.connectionpool test_telegram   https://api.telegram.org:443 "GET /botxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/getMe HTTP/1.1" 200 200
2020-11-03 11:01:30 DEBUG    telegram.bot  test_telegram   {'id': xxxxxxxxxx, 'first_name': 'Bot', 'is_bot': True, 'username': 'Bot'}
2020-11-03 11:01:30 DEBUG    telegram.bot  test_telegram   Exiting: get_me
2020-11-03 11:01:30 DEBUG    telegram      test_telegram   loading cached chat ids
2020-11-03 11:01:30 DEBUG    telegram      test_telegram   found 1 cached chat_ids: ['id=xxxxxxxxxx group=MyTeste1']
2020-11-03 11:01:30 DEBUG    telegram      test_telegram   all chat ids found in cache
2020-11-03 11:01:30 DEBUG    telegram      test_telegram   chat_ids=[<flexget.components.notify.notifiers.telegram.ChatIdEntry object at 0x7ff5d663aa20>]
2020-11-03 11:01:30 DEBUG    telegram      test_telegram   sending msg to telegram servers: Teste
2020-11-03 11:01:30 DEBUG    telegram.bot  test_telegram   Entering: send_message
2020-11-03 11:01:30 DEBUG    telegram.vendor.ptb_urllib3.urllib3.connectionpool test_telegram   https://api.telegram.org:443 "POST /botxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/sendMessage HTTP/1.1" 400 154
2020-11-03 11:01:30 WARNING  telegram      test_telegram   Failed to render message using parse mode Markdown. Falling back to basic parsing: Group migrated to supergroup. New chat id: xxxxxxxxxx
2020-11-03 11:01:30 DEBUG    telegram.bot  test_telegram   Entering: send_message
2020-11-03 11:01:30 DEBUG    telegram.vendor.ptb_urllib3.urllib3.connectionpool test_telegram   https://api.telegram.org:443 "POST /botxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/sendMessage HTTP/1.1" 400 154
2020-11-03 11:01:30 WARNING  notify        test_telegram   Error while sending notification to `telegram`: Group migrated to supergroup. New chat id: xxxxxxxxxx
```


Resolving patch:
diff --git a/flexget/components/notify/notifiers/telegram.py b/flexget/components/notify/notifiers/telegram.py
--- a/flexget/components/notify/notifiers/telegram.py
+++ b/flexget/components/notify/notifiers/telegram.py
@@ -10,7 +10,7 @@
 
 try:
     import telegram
-    from telegram.error import TelegramError
+    from telegram.error import TelegramError, ChatMigrated
     from telegram.utils.request import NetworkError
 except ImportError:
     telegram = None
@@ -192,11 +192,13 @@ def notify(self, title, message, config):
         """
         Send a Telegram notification
         """
+
+        session = Session()
         chat_ids = self._real_init(Session(), config)
 
         if not chat_ids:
             return
-        self._send_msgs(message, chat_ids)
+        self._send_msgs(message, chat_ids, session)
 
     def _parse_config(self, config):
         """
@@ -288,7 +290,18 @@ def _enforce_telegram_plugin_ver():
                 'old python-telegram-bot ({0})'.format(telegram.__version__)
             )
 
-    def _send_msgs(self, msg, chat_ids):
+    def _replace_chat_id(self, old_id, new_id, session):
+        upd_usernames, upd_fullnames, upd_groups = self._get_bot_updates()
+        for group in upd_groups:
+            grp = upd_groups.get(group)
+            if grp.id == new_id:
+                old_data = session.query(ChatIdEntry).filter(ChatIdEntry.id == old_id).first()
+                session.delete(old_data)
+                entry = ChatIdEntry(id=grp.id, group=grp.title)
+                self._update_db(session, [entry])
+                break
+
+    def _send_msgs(self, msg, chat_ids, session):
         kwargs = dict()
         if self._parse_mode == 'markdown':
             kwargs['parse_mode'] = telegram.ParseMode.MARKDOWN
@@ -299,6 +312,14 @@ def _send_msgs(self, msg, chat_ids):
             try:
                 logger.debug('sending msg to telegram servers: {}', msg)
                 self._bot.sendMessage(chat_id=chat_id, text=msg, **kwargs)
+            except ChatMigrated as e:
+                logger.debug("Chat migrated to id {}", e.new_chat_id)
+                try:
+                    self._bot.sendMessage(chat_id=e.new_chat_id, text=msg, **kwargs)
+                    self._replace_chat_id(chat_id, e.new_chat_id, session)
+                except TelegramError as e:
+                    raise PluginWarning(e.message)
+
             except TelegramError as e:
                 if kwargs.get('parse_mode'):
                     logger.warning(
@@ -497,7 +518,8 @@ def _get_bot_updates(self):
             elif update.channel_post:
                 chat = update.channel_post.chat
             else:
-                raise PluginError('Unknown update type encountered: %s' % update)
+                continue
+                # raise PluginError('Unknown update type encountered: %s' % update)
 
             if chat.type == 'private':
                 usernames[chat.username] = chat


Test patch: