Repository: Pycord-Development/pycord

Issue:
AttributeError: 'NoneType' object has no attribute 'get_thread'
### Summary

When upgrading from 2.0.0-rc.1 to 2.0.0, I'm getting this error.

### Reproduction Steps

My code calls `channel.history()` and iterates over messages in the channel. This is the trailing end of the stack trace I get:

```
    async for message in channel.history(limit=None, after=history_after):
  File "/home/circleci/.cache/pypoetry/virtualenvs/juniorguru-3aSsmiER-py3.8/lib/python3.8/site-packages/discord/iterators.py", line 125, in __anext__
    return await self.next()
  File "/home/circleci/.cache/pypoetry/virtualenvs/juniorguru-3aSsmiER-py3.8/lib/python3.8/site-packages/discord/iterators.py", line 325, in next
    await self.fill_messages()
  File "/home/circleci/.cache/pypoetry/virtualenvs/juniorguru-3aSsmiER-py3.8/lib/python3.8/site-packages/discord/iterators.py", line 359, in fill_messages
    await self.messages.put(self.state.create_message(channel=channel, data=element))
  File "/home/circleci/.cache/pypoetry/virtualenvs/juniorguru-3aSsmiER-py3.8/lib/python3.8/site-packages/discord/state.py", line 1693, in create_message
    return Message(state=self, channel=channel, data=data)
  File "/home/circleci/.cache/pypoetry/virtualenvs/juniorguru-3aSsmiER-py3.8/lib/python3.8/site-packages/discord/message.py", line 764, in __init__
    ref.resolved = self.__class__(channel=chan, data=resolved, state=state)  # type: ignore
  File "/home/circleci/.cache/pypoetry/virtualenvs/juniorguru-3aSsmiER-py3.8/lib/python3.8/site-packages/discord/message.py", line 776, in __init__
    self.thread = Thread(guild=self.guild, state=self._state, data=data["thread"])
  File "/home/circleci/.cache/pypoetry/virtualenvs/juniorguru-3aSsmiER-py3.8/lib/python3.8/site-packages/discord/threads.py", line 160, in __init__
    self._from_data(data)
  File "/home/circleci/.cache/pypoetry/virtualenvs/juniorguru-3aSsmiER-py3.8/lib/python3.8/site-packages/discord/threads.py", line 190, in _from_data
    if thread := self.guild.get_thread(self.id) and data.pop("_invoke_flag", False):
AttributeError: 'NoneType' object has no attribute 'get_thread'
```

### Minimal Reproducible Code

_No response_

### Expected Results

Pycord should be able to instantiate and return the Message object.

### Actual Results

Pycord crashes as `self.guild` probably isn't set.

### Intents

guilds, members, message_content

### System Information

- Python v3.8.7-final
- py-cord v2.0.0-candidate
    - py-cord pkg_resources: v2.0.0rc1
- aiohttp v3.8.1
- system info: Darwin 21.5.0 Darwin Kernel Version 21.5.0: Tue Apr 26 21:08:29 PDT 2022; root:xnu-8020.121.3~4/RELEASE_ARM64_T8101

### Checklist

- [X] I have searched the open issues for duplicates.
- [X] I have shown the entire traceback, if possible.
- [X] I have removed my token from display, if visible.

### Additional Context

Possibly related to @baronkobama's https://github.com/Pycord-Development/pycord/pull/1447


Discussion:
It seems to be specific to the data. I'm able to fetch hundreds of threads and other channels and read them, but at certain point the same code crashes with the exception. I'll investigate further and report if I'm able to corner this out.
#1447 isn't related
What's the type of channel that you have (as in object type)? Is it by chance a PartialMessageable?
The type is Thread. I'm still working on figuring out what's happening, but my time is a bit fragmented these days. I made certain progress in a sense as I think it crashes on just a few specific threads, one or two. When the code encounters them, the exception happens. I think I might be able to come back with a minimal reproducible example soon.
This is minimal reproducible example, sadly dependent on specific data from the server.

```python
import os

import discord

intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)

@client.event
async def on_ready():
    # my server
    guild = client.get_guild(769966886598737931)

    # problematic thread (but hundreds of others work just fine,
    # also 2.0.0-rc.1 works just fine)
    thread = await guild.fetch_channel(923161263243165757)
    print(repr(thread), repr(thread.guild))

    # the following line raises
    #
    #   ...
    #   File "/Users/honza/Library/Caches/pypoetry/virtualenvs/juniorguru-Lgaxwd2n-py3.8/lib/python3.8/site-packages/discord/threads.py", line 191, in _from_data
    #     if thread := self.guild.get_thread(self.id) and data.pop("_invoke_flag", False):
    # AttributeError: 'NoneType' object has no attribute 'get_thread'
    async for message in thread.history():
        pass


client.run(os.getenv('DISCORD_API_KEY'))
```

It prints the following output:

```
<Thread id=923161263243165757 name='kalendář' parent=oznámení owner_id=652142810291765248 locked=False archived=True> <Guild id=769966886598737931 name='junior.guru' shard_id=0 chunked=False member_count=361>
```

If I open `/Users/honza/Library/Caches/pypoetry/virtualenvs/juniorguru-Lgaxwd2n-py3.8/lib/python3.8/site-packages/discord/threads.py` and edit it like this:

```diff
 def __init__(self, *, guild: Guild, state: ConnectionState, data: ThreadPayload):
+        print('DBG INIT THREAD:', repr(guild), repr(state), repr(data))
         self._state: ConnectionState = state
         self.guild = guild
         self._members: Dict[int, ThreadMember] = {}
         self._from_data(data)
```

I get the following as the output:

```
$ python minimal.py 
DBG INIT THREAD: <Guild id=769966886598737931 name='junior.guru' shard_id=0 chunked=False member_count=361> <discord.state.ConnectionState object at 0x10d55eee0> {'type': 11, 'total_message_sent': 21, 'thread_metadata': {'locked': False, 'create_timestamp': '2022-07-06T21:16:23.288000+00:00', 'auto_archive_duration': 10080, 'archived': False, 'archive_timestamp': '2022-07-06T21:16:23.288000+00:00'}, 'rate_limit_per_user': 0, 'parent_id': '769966887055392768', 'owner_id': '979102106776641577', 'name': '/// various different threads, name redacted ///', 'message_count': 20, 'member_count': 7, 'last_message_id': '995414821065474128', 'id': '994351128932262030', 'guild_id': '769966886598737931', 'flags': 0}
DBG INIT THREAD: <Guild id=769966886598737931 name='junior.guru' shard_id=0 chunked=False member_count=361> <discord.state.ConnectionState object at 0x10d55eee0> {'type': 11, 'total_message_sent': 1, 'thread_metadata': {'locked': False, 'create_timestamp': '2022-07-12T07:31:57.639359+00:00', 'auto_archive_duration': 10080, 'archived': False, 'archive_timestamp': '2022-07-12T07:31:57.639359+00:00'}, 'rate_limit_per_user': 0, 'parent_id': '769966887055392768', 'owner_id': '652142810291765248', 'name': '/// various different threads, name redacted ///', 'message_count': 1, 'member_count': 2, 'last_message_id': '996317983561486367', 'id': '996316886037975161', 'guild_id': '769966886598737931', 'flags': 0}
DBG INIT THREAD: <Guild id=769966886598737931 name='junior.guru' shard_id=0 chunked=False member_count=361> <discord.state.ConnectionState object at 0x10d55eee0> {'type': 11, 'total_message_sent': 12, 'thread_metadata': {'locked': False, 'create_timestamp': '2022-06-07T06:19:27.857000+00:00', 'auto_archive_duration': 10080, 'archived': False, 'archive_timestamp': '2022-07-07T19:52:48.237867+00:00'}, 'rate_limit_per_user': 0, 'parent_id': '788826407412170752', 'owner_id': '652142810291765248', 'name': '/// various different threads, name redacted ///', 'message_count': 12, 'member_count': 3, 'last_message_id': '985083007713038377', 'id': '983615979881906197', 'guild_id': '769966886598737931', 'flags': 0}
DBG INIT THREAD: <Guild id=769966886598737931 name='junior.guru' shard_id=0 chunked=False member_count=361> <discord.state.ConnectionState object at 0x10d55eee0> {'type': 11, 'total_message_sent': 3, 'thread_metadata': {'locked': False, 'create_timestamp': '2022-07-04T11:26:09.010251+00:00', 'auto_archive_duration': 10080, 'archived': False, 'archive_timestamp': '2022-07-04T11:26:09.010251+00:00'}, 'rate_limit_per_user': 0, 'parent_id': '789107031939481641', 'owner_id': '528615697757110290', 'name': '/// various different threads, name redacted ///', 'message_count': 6, 'member_count': 3, 'last_message_id': '994707379205701772', 'id': '993476732751462400', 'guild_id': '769966886598737931', 'flags': 0}
DBG INIT THREAD: <Guild id=769966886598737931 name='junior.guru' shard_id=0 chunked=False member_count=361> <discord.state.ConnectionState object at 0x10d55eee0> {'type': 11, 'total_message_sent': 5, 'thread_metadata': {'locked': False, 'create_timestamp': '2022-06-29T13:29:33.206000+00:00', 'auto_archive_duration': 10080, 'archived': False, 'archive_timestamp': '2022-07-10T20:38:01.227277+00:00'}, 'rate_limit_per_user': 0, 'parent_id': '797040163325870092', 'owner_id': '819684326261260309', 'name': '/// various different threads, name redacted ///', 'message_count': 5, 'member_count': 6, 'last_message_id': '995791024968454196', 'id': '991696931074089090', 'guild_id': '769966886598737931', 'flags': 0}
DBG INIT THREAD: <Guild id=769966886598737931 name='junior.guru' shard_id=0 chunked=False member_count=361> <discord.state.ConnectionState object at 0x10d55eee0> {'type': 11, 'total_message_sent': 1, 'thread_metadata': {'locked': False, 'create_timestamp': '2022-07-06T15:48:25.899612+00:00', 'auto_archive_duration': 10080, 'archived': False, 'archive_timestamp': '2022-07-06T15:48:25.899612+00:00'}, 'rate_limit_per_user': 0, 'parent_id': '806621830383271937', 'owner_id': '211569606450479104', 'name': '/// various different threads, name redacted ///', 'message_count': 1, 'member_count': 2, 'last_message_id': '994268598942040254', 'id': '994259801385209896', 'guild_id': '769966886598737931', 'flags': 0}
DBG INIT THREAD: <Guild id=769966886598737931 name='junior.guru' shard_id=0 chunked=False member_count=361> <discord.state.ConnectionState object at 0x10d55eee0> {'type': 11, 'total_message_sent': 9, 'thread_metadata': {'locked': False, 'create_timestamp': '2022-07-09T14:08:54.385687+00:00', 'auto_archive_duration': 10080, 'archived': False, 'archive_timestamp': '2022-07-09T14:08:54.385687+00:00'}, 'rate_limit_per_user': 0, 'parent_id': '815906954534191117', 'owner_id': '652142810291765248', 'name': '/// various different threads, name redacted ///', 'message_count': 9, 'member_count': 4, 'last_message_id': '995965527619010570', 'id': '995310757107470388', 'guild_id': '769966886598737931', 'flags': 0}
DBG INIT THREAD: <Guild id=769966886598737931 name='junior.guru' shard_id=0 chunked=False member_count=361> <discord.state.ConnectionState object at 0x10d55eee0> {'type': 11, 'total_message_sent': 7, 'thread_metadata': {'locked': False, 'create_timestamp': '2022-07-11T13:55:11.464556+00:00', 'auto_archive_duration': 10080, 'archived': False, 'archive_timestamp': '2022-07-11T13:55:11.464556+00:00'}, 'rate_limit_per_user': 0, 'parent_id': '815906954534191117', 'owner_id': '419662350874837003', 'name': '/// various different threads, name redacted ///', 'message_count': 7, 'member_count': 5, 'last_message_id': '996342122145914880', 'id': '996045611554062406', 'guild_id': '769966886598737931', 'flags': 0}
DBG INIT THREAD: <Guild id=769966886598737931 name='junior.guru' shard_id=0 chunked=False member_count=361> <discord.state.ConnectionState object at 0x10d55eee0> {'type': 11, 'total_message_sent': 67, 'thread_metadata': {'locked': False, 'create_timestamp': '2022-06-16T07:18:30.491000+00:00', 'auto_archive_duration': 10080, 'archived': False, 'archive_timestamp': '2022-06-16T07:18:30.491000+00:00'}, 'rate_limit_per_user': 0, 'parent_id': '839059491432431616', 'owner_id': '791020144661889054', 'name': '/// various different threads, name redacted ///', 'message_count': 67, 'member_count': 8, 'last_message_id': '994717487453184000', 'id': '986884614817730570', 'guild_id': '769966886598737931', 'flags': 0}
DBG INIT THREAD: <Guild id=769966886598737931 name='junior.guru' shard_id=0 chunked=False member_count=361> <discord.state.ConnectionState object at 0x10d55eee0> {'type': 11, 'total_message_sent': 13, 'thread_metadata': {'locked': False, 'create_timestamp': '2022-06-28T12:34:15.276094+00:00', 'auto_archive_duration': 10080, 'archived': False, 'archive_timestamp': '2022-06-28T12:34:15.276094+00:00'}, 'rate_limit_per_user': 0, 'parent_id': '839059491432431616', 'owner_id': '668226181769986078', 'name': '/// various different threads, name redacted ///', 'message_count': 13, 'member_count': 7, 'last_message_id': '994709821385359490', 'id': '991253586312953976', 'guild_id': '769966886598737931', 'flags': 0}
DBG INIT THREAD: <Guild id=769966886598737931 name='junior.guru' shard_id=0 chunked=False member_count=361> <discord.state.ConnectionState object at 0x10d55eee0> {'type': 11, 'total_message_sent': 22, 'thread_metadata': {'locked': False, 'create_timestamp': '2022-06-28T12:33:37.011027+00:00', 'auto_archive_duration': 10080, 'archived': False, 'archive_timestamp': '2022-06-28T12:33:37.011027+00:00'}, 'rate_limit_per_user': 0, 'parent_id': '839059491432431616', 'owner_id': '668226181769986078', 'name': '/// various different threads, name redacted ///', 'message_count': 22, 'member_count': 4, 'last_message_id': '994715761803284531', 'id': '991263930502615050', 'guild_id': '769966886598737931', 'flags': 0}
DBG INIT THREAD: <Guild id=769966886598737931 name='junior.guru' shard_id=0 chunked=False member_count=361> <discord.state.ConnectionState object at 0x10d55eee0> {'type': 11, 'total_message_sent': 2, 'thread_metadata': {'locked': False, 'create_timestamp': '2022-07-12T08:24:49.633422+00:00', 'auto_archive_duration': 10080, 'archived': False, 'archive_timestamp': '2022-07-12T08:24:49.633422+00:00'}, 'rate_limit_per_user': 0, 'parent_id': '839059491432431616', 'owner_id': '652142810291765248', 'name': '/// various different threads, name redacted ///', 'message_count': 2, 'member_count': 2, 'last_message_id': '996332666368565328', 'id': '996317922869907576', 'guild_id': '769966886598737931', 'flags': 0}
DBG INIT THREAD: <Guild id=769966886598737931 name='junior.guru' shard_id=0 chunked=False member_count=361> <discord.state.ConnectionState object at 0x10d55eee0> {'type': 11, 'total_message_sent': 57, 'thread_metadata': {'locked': False, 'create_timestamp': '2022-07-11T06:30:25.542000+00:00', 'auto_archive_duration': 10080, 'archived': False, 'archive_timestamp': '2022-07-11T06:30:25.542000+00:00'}, 'rate_limit_per_user': 0, 'parent_id': '864434121409560616', 'owner_id': '414887173154930698', 'name': '/// various different threads, name redacted ///', 'message_count': 57, 'member_count': 3, 'last_message_id': '995968766099853332', 'id': '995940108513587210', 'guild_id': '769966886598737931', 'flags': 0}
DBG INIT THREAD: <Guild id=769966886598737931 name='junior.guru' shard_id=0 chunked=False member_count=361> <discord.state.ConnectionState object at 0x10d55eee0> {'type': 11, 'total_message_sent': 8, 'thread_metadata': {'locked': False, 'create_timestamp': '2022-06-15T12:45:27.435000+00:00', 'auto_archive_duration': 10080, 'archived': False, 'archive_timestamp': '2022-07-07T20:52:02.192985+00:00'}, 'rate_limit_per_user': 0, 'parent_id': '878937534464417822', 'owner_id': '867769325879296030', 'name': '/// various different threads, name redacted ///', 'message_count': 8, 'member_count': 2, 'last_message_id': '994707449598705804', 'id': '986612403787694130', 'guild_id': '769966886598737931', 'flags': 0}
DBG INIT THREAD: <Guild id=769966886598737931 name='junior.guru' shard_id=0 chunked=False member_count=361> <discord.state.ConnectionState object at 0x10d55eee0> {'type': 11, 'total_message_sent': 1, 'thread_metadata': {'locked': False, 'create_timestamp': '2022-07-01T09:53:26.915000+00:00', 'auto_archive_duration': 10080, 'archived': False, 'archive_timestamp': '2022-07-01T09:53:26.915000+00:00'}, 'rate_limit_per_user': 0, 'parent_id': '878937534464417822', 'owner_id': '788486062430355497', 'name': '/// various different threads, name redacted ///', 'message_count': 4, 'member_count': 3, 'last_message_id': '994682580324593786', 'id': '992367322239094815', 'guild_id': '769966886598737931', 'flags': 0}
DBG INIT THREAD: <Guild id=769966886598737931 name='junior.guru' shard_id=0 chunked=False member_count=361> <discord.state.ConnectionState object at 0x10d55eee0> {'type': 11, 'total_message_sent': 2, 'thread_metadata': {'locked': False, 'create_timestamp': '2022-07-06T11:43:15.714000+00:00', 'auto_archive_duration': 10080, 'archived': False, 'archive_timestamp': '2022-07-06T11:43:15.714000+00:00'}, 'rate_limit_per_user': 0, 'parent_id': '878937534464417822', 'owner_id': '417334190674018305', 'name': '/// various different threads, name redacted ///', 'message_count': 2, 'member_count': 2, 'last_message_id': '994580844465356911', 'id': '994206896993091625', 'guild_id': '769966886598737931', 'flags': 0}
DBG INIT THREAD: <Guild id=769966886598737931 name='junior.guru' shard_id=0 chunked=False member_count=361> <discord.state.ConnectionState object at 0x10d55eee0> {'type': 11, 'total_message_sent': 11, 'thread_metadata': {'locked': False, 'create_timestamp': '2022-07-06T18:42:01.289000+00:00', 'auto_archive_duration': 10080, 'archived': False, 'archive_timestamp': '2022-07-06T18:42:01.289000+00:00'}, 'rate_limit_per_user': 0, 'parent_id': '878937534464417822', 'owner_id': '788486062430355497', 'name': '/// various different threads, name redacted ///', 'message_count': 11, 'member_count': 5, 'last_message_id': '994344730924159107', 'id': '994312281292816507', 'guild_id': '769966886598737931', 'flags': 0}
DBG INIT THREAD: <Guild id=769966886598737931 name='junior.guru' shard_id=0 chunked=False member_count=361> <discord.state.ConnectionState object at 0x10d55eee0> {'type': 11, 'total_message_sent': 42, 'thread_metadata': {'locked': False, 'create_timestamp': '2022-07-07T08:37:04.049000+00:00', 'auto_archive_duration': 10080, 'archived': False, 'archive_timestamp': '2022-07-07T08:37:04.049000+00:00'}, 'rate_limit_per_user': 0, 'parent_id': '878937534464417822', 'owner_id': '788486062430355497', 'name': '/// various different threads, name redacted ///', 'message_count': 42, 'member_count': 3, 'last_message_id': '995349133739167887', 'id': '994522427499483248', 'guild_id': '769966886598737931', 'flags': 0}
DBG INIT THREAD: <Guild id=769966886598737931 name='junior.guru' shard_id=0 chunked=False member_count=361> <discord.state.ConnectionState object at 0x10d55eee0> {'type': 11, 'total_message_sent': 21, 'thread_metadata': {'locked': False, 'create_timestamp': '2022-07-09T15:52:07.014000+00:00', 'auto_archive_duration': 10080, 'archived': False, 'archive_timestamp': '2022-07-09T15:52:07.014000+00:00'}, 'rate_limit_per_user': 0, 'parent_id': '878937534464417822', 'owner_id': '979102106776641577', 'name': '/// various different threads, name redacted ///', 'message_count': 21, 'member_count': 5, 'last_message_id': '996015800941027338', 'id': '995356687001206814', 'guild_id': '769966886598737931', 'flags': 0}
DBG INIT THREAD: <Guild id=769966886598737931 name='junior.guru' shard_id=0 chunked=False member_count=361> <discord.state.ConnectionState object at 0x10d55eee0> {'type': 11, 'total_message_sent': 14, 'thread_metadata': {'locked': False, 'create_timestamp': '2022-07-11T10:14:08.219000+00:00', 'auto_archive_duration': 10080, 'archived': False, 'archive_timestamp': '2022-07-11T10:14:08.219000+00:00'}, 'rate_limit_per_user': 0, 'parent_id': '878937534464417822', 'owner_id': '809003071014961174', 'name': '/// various different threads, name redacted ///', 'message_count': 12, 'member_count': 2, 'last_message_id': '996034744376635422', 'id': '995996407301410906', 'guild_id': '769966886598737931', 'flags': 0}
DBG INIT THREAD: <Guild id=769966886598737931 name='junior.guru' shard_id=0 chunked=False member_count=361> <discord.state.ConnectionState object at 0x10d55eee0> {'type': 11, 'total_message_sent': 9, 'thread_metadata': {'locked': False, 'create_timestamp': '2022-07-11T11:21:25.649000+00:00', 'auto_archive_duration': 10080, 'archived': False, 'archive_timestamp': '2022-07-11T11:21:25.649000+00:00'}, 'rate_limit_per_user': 0, 'parent_id': '878937534464417822', 'owner_id': '562826657208205326', 'name': '/// various different threads, name redacted ///', 'message_count': 9, 'member_count': 2, 'last_message_id': '996037005890814023', 'id': '996013341510209566', 'guild_id': '769966886598737931', 'flags': 0}
DBG INIT THREAD: <Guild id=769966886598737931 name='junior.guru' shard_id=0 chunked=False member_count=361> <discord.state.ConnectionState object at 0x10d55eee0> {'type': 11, 'total_message_sent': 1, 'thread_metadata': {'locked': False, 'create_timestamp': '2022-07-12T12:47:03.516000+00:00', 'auto_archive_duration': 10080, 'archived': False, 'archive_timestamp': '2022-07-12T12:47:03.516000+00:00'}, 'rate_limit_per_user': 0, 'parent_id': '878937534464417822', 'owner_id': '559096502249586788', 'name': '/// various different threads, name redacted ///', 'message_count': 1, 'member_count': 2, 'last_message_id': '996397281932750869', 'id': '996397279151915008', 'guild_id': '769966886598737931', 'flags': 0}
DBG INIT THREAD: <Guild id=769966886598737931 name='junior.guru' shard_id=0 chunked=False member_count=361> <discord.state.ConnectionState object at 0x10d55eee0> {'type': 11, 'total_message_sent': 3, 'thread_metadata': {'locked': False, 'create_timestamp': '2022-07-12T12:53:10.995000+00:00', 'auto_archive_duration': 10080, 'archived': False, 'archive_timestamp': '2022-07-12T12:53:10.995000+00:00'}, 'rate_limit_per_user': 0, 'parent_id': '878937534464417822', 'owner_id': '559096502249586788', 'name': '/// various different threads, name redacted ///', 'message_count': 3, 'member_count': 2, 'last_message_id': '996398993783410759', 'id': '996398820470575234', 'guild_id': '769966886598737931', 'flags': 0}
DBG INIT THREAD: <Guild id=769966886598737931 name='junior.guru' shard_id=0 chunked=False member_count=361> <discord.state.ConnectionState object at 0x10d55eee0> {'id': '923161263243165757', 'guild_id': '769966886598737931', 'parent_id': '789046675247333397', 'owner_id': '652142810291765248', 'type': 10, 'name': 'kalendář', 'last_message_id': '923188070696767488', 'thread_metadata': {'archived': True, 'archive_timestamp': '2021-12-25T12:27:32.552000+00:00', 'auto_archive_duration': 4320, 'locked': False}, 'message_count': 6, 'member_count': 2, 'rate_limit_per_user': 0, 'flags': 0, 'total_message_sent': 6}
<Thread id=923161263243165757 name='kalendář' parent=oznámení owner_id=652142810291765248 locked=False archived=True> <Guild id=769966886598737931 name='junior.guru' shard_id=0 chunked=False member_count=361>
DBG INIT THREAD: None <discord.state.ConnectionState object at 0x10d55eee0> {'id': '923161263243165757', 'guild_id': '769966886598737931', 'parent_id': '789046675247333397', 'owner_id': '652142810291765248', 'type': 10, 'name': 'kalendář', 'last_message_id': '923188070696767488', 'thread_metadata': {'archived': True, 'archive_timestamp': '2021-12-25T12:27:32.552000+00:00', 'auto_archive_duration': 4320, 'locked': False}, 'message_count': 6, 'member_count': 2, 'rate_limit_per_user': 0, 'flags': 0, 'total_message_sent': 6}
Ignoring exception in on_ready
Traceback (most recent call last):
  File "/Users/honza/Library/Caches/pypoetry/virtualenvs/juniorguru-Lgaxwd2n-py3.8/lib/python3.8/site-packages/discord/client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "minimal.py", line 26, in on_ready
    async for message in thread.history():
  File "/Users/honza/Library/Caches/pypoetry/virtualenvs/juniorguru-Lgaxwd2n-py3.8/lib/python3.8/site-packages/discord/iterators.py", line 125, in __anext__
    return await self.next()
  File "/Users/honza/Library/Caches/pypoetry/virtualenvs/juniorguru-Lgaxwd2n-py3.8/lib/python3.8/site-packages/discord/iterators.py", line 325, in next
    await self.fill_messages()
  File "/Users/honza/Library/Caches/pypoetry/virtualenvs/juniorguru-Lgaxwd2n-py3.8/lib/python3.8/site-packages/discord/iterators.py", line 359, in fill_messages
    await self.messages.put(self.state.create_message(channel=channel, data=element))
  File "/Users/honza/Library/Caches/pypoetry/virtualenvs/juniorguru-Lgaxwd2n-py3.8/lib/python3.8/site-packages/discord/state.py", line 1693, in create_message
    return Message(state=self, channel=channel, data=data)
  File "/Users/honza/Library/Caches/pypoetry/virtualenvs/juniorguru-Lgaxwd2n-py3.8/lib/python3.8/site-packages/discord/message.py", line 764, in __init__
    ref.resolved = self.__class__(channel=chan, data=resolved, state=state)  # type: ignore
  File "/Users/honza/Library/Caches/pypoetry/virtualenvs/juniorguru-Lgaxwd2n-py3.8/lib/python3.8/site-packages/discord/message.py", line 776, in __init__
    self.thread = Thread(guild=self.guild, state=self._state, data=data["thread"])
  File "/Users/honza/Library/Caches/pypoetry/virtualenvs/juniorguru-Lgaxwd2n-py3.8/lib/python3.8/site-packages/discord/threads.py", line 161, in __init__
    self._from_data(data)
  File "/Users/honza/Library/Caches/pypoetry/virtualenvs/juniorguru-Lgaxwd2n-py3.8/lib/python3.8/site-packages/discord/threads.py", line 191, in _from_data
    if thread := self.guild.get_thread(self.id) and data.pop("_invoke_flag", False):
AttributeError: 'NoneType' object has no attribute 'get_thread'
```

As you can see, for some reason many other threads are instantiated first (probably as hydrating objects from initial server response about client and guild). Then there's the problematic thread instantiated, perhaps after the fetch call in my minimal code. It has guild attached. But then, it's being instantiated again for some reason, and then the guild is missing.
So far, after scanning the payloads, I've noticed the thread that is failing to have a guild attribute is different from the others in three ways:

* The failing thread is a news thread (type 10) instead of a public thread (type 11).
* The failing thread is archived while the rest are not.
* The failing thread is missing the `create_timestamp` field in its `thread_metadata`.

While I'm not sure how this would affect the guild attribute being created, it's worth pointing this out as it is _likely_ the source of the problem. However, without having the means to reproduce this issue, I'm unable to really determine what's happening here at the moment.
I think the code (which reads all my server history and analyses it) has been able to fail on a few other threads, too. I can determine those and see, if they have some common traits. I'd say that the fact this one is archived can be crossed out from the list of culprit candidates as the code definitely successfully reads hundreds of other archived threads just fine. I suspect

- the type (TBH I don't have many threads in the news channel, so possibly?)
- or the timestamp (but that is something that Discord API just gives back this way and it isn't on my side, right?).
Another thing that just came to my mind is I could bisect which commit between the rc and v2 starts to crash the code 🤔 
Debugging further. The problem is actually in `message.py`, where messages get instantiated. I call `.history()` on the thread, which requests the API and then instantiates individual messages.

In the `__init__()` method of `Message()`, there is first

```python
try:
    # if the channel doesn't have a guild attribute, we handle that
    self.guild = channel.guild  # type: ignore
except AttributeError:
    self.guild = state._get_guild(utils._get_as_snowflake(data, "guild_id"))
```

then later below

```python
self.thread = Thread(guild=self.guild, state=self._state, data=data["thread"])
```

The first snippet sets `self.guild` to `None`, which is why the second snippet explodes with guild missing. It is not problem in requesting and instantiating the thread itself, but in reading its messages and then backreferencing the thread of the individual messages when instantiating those.

Further debugging has shown me that for 11 messages from the thread this works out well, but then the first snippet throws the `AttributeError`, specifically

```
'DMChannel' object has no attribute 'guild' <DMChannel id=789046675247333397 recipient=None>
```

This is very interesting, because we're talking about a thread within a news text channel, 11 messages from the thread get correctly backreferenced to the thread itself, but then there is something which has the news channel as a parent (id 789046675247333397) and it thinks that it is a DM channel! 🤯 This is the data sent to the Message object:

```python
{'attachments': [],
 'author': {'avatar': 'f05f801793b03a1bf5fa711cd1830385',
            'avatar_decoration': None,
            'discriminator': '4722',
            'id': '668226181769986078',
            'public_flags': 0,
            'username': 'honzajavorek'},
 'channel_id': '789046675247333397',
 'components': [],
 'content': 'Vyrobil jsem ten iCalendar feed, jak ho chtěl '
            '<@!652142810291765248> a možná ještě i někdo další  🗓️ Když si to '
            'přidáte do svého kalendáře (jako živé URL, nestahovat jako '
            'soubor), měly by se vám tam automaticky objevovat JG akce '
            'https://junior.guru/api/events.ics Akorát teď není lednová ještě '
            'uveřejněná (čekám na detaily od speakera), tak se vám zatím '
            'objeví jen přednášky zpětně 😅 Každopádně budu rád, když mi to '
            'pomůžete otestovat, kdo to využijete.',
 'edited_timestamp': None,
 'embeds': [],
 'flags': 32,
 'id': '923161263243165757',
 'mention_everyone': False,
 'mention_roles': [],
 'mentions': [{'avatar': '24a0e0ac4a48be5a9870e4c67c760bb2',
               'avatar_decoration': None,
               'discriminator': '1656',
               'id': '652142810291765248',
               'public_flags': 0,
               'username': 'benabraham'}],
 'pinned': False,
 'thread': {'flags': 0,
            'guild_id': '769966886598737931',
            'id': '923161263243165757',
            'last_message_id': '923188070696767488',
            'member_count': 2,
            'message_count': 6,
            'name': 'kalendář',
            'owner_id': '652142810291765248',
            'parent_id': '789046675247333397',
            'rate_limit_per_user': 0,
            'thread_metadata': {'archive_timestamp': '2021-12-25T12:27:32.552000+00:00',
                                'archived': True,
                                'auto_archive_duration': 4320,
                                'locked': False},
            'total_message_sent': 6,
            'type': 10},
 'timestamp': '2021-12-22T10:33:16.664000+00:00',
 'tts': False,
 'type': 0}
```

The data doesn't cause the crash, the wrong type of the channel does. Interestingly, this isn't a message from within the thread, but the parent message of the thread. I guess the code tries to instantiate it as part of backreferencing to the parent of the thread and not as a part of the thread history. The stack trace points me to these two lines in code:

```python
# the channel will be the correct type here
ref.resolved = self.__class__(channel=chan, data=resolved, state=state)  # type: ignore
```

It seems that the channel **is not** the correct type here, but I don't know yet why is that.
This is the data from which the `thread.history()` attempts to populate the messages:

<details>
<summary>(click here to expand)</summary>

```python
[
    {
        "id": "923188070696767488",
        "type": 19,
        "content": "ajó, tak to je cajk",
        "channel_id": "923161263243165757",
        "author": {
            "id": "652142810291765248",
            "username": "benabraham",
            "avatar": "24a0e0ac4a48be5a9870e4c67c760bb2",
            "avatar_decoration": None,
            "discriminator": "1656",
            "public_flags": 0,
        },
        "attachments": [],
        "embeds": [],
        "mentions": [
            {
                "id": "668226181769986078",
                "username": "honzajavorek",
                "avatar": "f05f801793b03a1bf5fa711cd1830385",
                "avatar_decoration": None,
                "discriminator": "4722",
                "public_flags": 0,
            }
        ],
        "mention_roles": [],
        "pinned": False,
        "mention_everyone": False,
        "tts": False,
        "timestamp": "2021-12-22T12:19:48.059000 00:00",
        "edited_timestamp": None,
        "flags": 0,
        "components": [],
        "message_reference": {
            "channel_id": "923161263243165757",
            "guild_id": "769966886598737931",
            "message_id": "923186328835866684",
        },
        "referenced_message": {
            "id": "923186328835866684",
            "type": 19,
            "content": "Data jsou tam v UTC, tvůj kalendář by to měl zobrazit ve tvojí timezone. Máš minulé přednášky v šest večer?",
            "channel_id": "923161263243165757",
            "author": {
                "id": "668226181769986078",
                "username": "honzajavorek",
                "avatar": "f05f801793b03a1bf5fa711cd1830385",
                "avatar_decoration": None,
                "discriminator": "4722",
                "public_flags": 0,
            },
            "attachments": [],
            "embeds": [],
            "mentions": [
                {
                    "id": "652142810291765248",
                    "username": "benabraham",
                    "avatar": "24a0e0ac4a48be5a9870e4c67c760bb2",
                    "avatar_decoration": None,
                    "discriminator": "1656",
                    "public_flags": 0,
                }
            ],
            "mention_roles": [],
            "pinned": False,
            "mention_everyone": False,
            "tts": False,
            "timestamp": "2021-12-22T12:12:52.767000 00:00",
            "edited_timestamp": None,
            "flags": 0,
            "components": [],
            "message_reference": {
                "channel_id": "923161263243165757",
                "guild_id": "769966886598737931",
                "message_id": "923181935247896586",
            },
        },
    },
    {
        "id": "923186514534481920",
        "type": 19,
        "content": "Budou snad později. Čekám, až to přidají do Python knihovny. Sleduju ten pull request a každý den tam jsou teď nové commity 😄",
        "channel_id": "923161263243165757",
        "author": {
            "id": "668226181769986078",
            "username": "honzajavorek",
            "avatar": "f05f801793b03a1bf5fa711cd1830385",
            "avatar_decoration": None,
            "discriminator": "4722",
            "public_flags": 0,
        },
        "attachments": [],
        "embeds": [],
        "mentions": [
            {
                "id": "652142810291765248",
                "username": "benabraham",
                "avatar": "24a0e0ac4a48be5a9870e4c67c760bb2",
                "avatar_decoration": None,
                "discriminator": "1656",
                "public_flags": 0,
            }
        ],
        "mention_roles": [],
        "pinned": False,
        "mention_everyone": False,
        "tts": False,
        "timestamp": "2021-12-22T12:13:37.041000 00:00",
        "edited_timestamp": None,
        "flags": 0,
        "components": [],
        "message_reference": {
            "channel_id": "923161263243165757",
            "guild_id": "769966886598737931",
            "message_id": "923182050876465152",
        },
        "referenced_message": {
            "id": "923182050876465152",
            "type": 0,
            "content": "nevidím tam události z klubu (vím, že jdou ručně přidávat, odsud, ale…)",
            "channel_id": "923161263243165757",
            "author": {
                "id": "652142810291765248",
                "username": "benabraham",
                "avatar": "24a0e0ac4a48be5a9870e4c67c760bb2",
                "avatar_decoration": None,
                "discriminator": "1656",
                "public_flags": 0,
            },
            "attachments": [],
            "embeds": [],
            "mentions": [],
            "mention_roles": [],
            "pinned": False,
            "mention_everyone": False,
            "tts": False,
            "timestamp": "2021-12-22T11:55:52.822000 00:00",
            "edited_timestamp": None,
            "flags": 0,
            "components": [],
        },
        "reactions": [{"emoji": {"id": None, "name": "🆗"}, "count": 1, "me": False}],
    },
    {
        "id": "923186328835866684",
        "type": 19,
        "content": "Data jsou tam v UTC, tvůj kalendář by to měl zobrazit ve tvojí timezone. Máš minulé přednášky v šest večer?",
        "channel_id": "923161263243165757",
        "author": {
            "id": "668226181769986078",
            "username": "honzajavorek",
            "avatar": "f05f801793b03a1bf5fa711cd1830385",
            "avatar_decoration": None,
            "discriminator": "4722",
            "public_flags": 0,
        },
        "attachments": [],
        "embeds": [],
        "mentions": [
            {
                "id": "652142810291765248",
                "username": "benabraham",
                "avatar": "24a0e0ac4a48be5a9870e4c67c760bb2",
                "avatar_decoration": None,
                "discriminator": "1656",
                "public_flags": 0,
            }
        ],
        "mention_roles": [],
        "pinned": False,
        "mention_everyone": False,
        "tts": False,
        "timestamp": "2021-12-22T12:12:52.767000 00:00",
        "edited_timestamp": None,
        "flags": 0,
        "components": [],
        "message_reference": {
            "channel_id": "923161263243165757",
            "guild_id": "769966886598737931",
            "message_id": "923181935247896586",
        },
        "referenced_message": {
            "id": "923181935247896586",
            "type": 0,
            "content": "ta timezona je asi špatně (a na rozdíl od name to nemůžu upravit)",
            "channel_id": "923161263243165757",
            "author": {
                "id": "652142810291765248",
                "username": "benabraham",
                "avatar": "24a0e0ac4a48be5a9870e4c67c760bb2",
                "avatar_decoration": None,
                "discriminator": "1656",
                "public_flags": 0,
            },
            "attachments": [],
            "embeds": [],
            "mentions": [],
            "mention_roles": [],
            "pinned": False,
            "mention_everyone": False,
            "tts": False,
            "timestamp": "2021-12-22T11:55:25.254000 00:00",
            "edited_timestamp": None,
            "flags": 0,
            "components": [],
        },
    },
    {
        "id": "923182050876465152",
        "type": 0,
        "content": "nevidím tam události z klubu (vím, že jdou ručně přidávat, odsud, ale…)",
        "channel_id": "923161263243165757",
        "author": {
            "id": "652142810291765248",
            "username": "benabraham",
            "avatar": "24a0e0ac4a48be5a9870e4c67c760bb2",
            "avatar_decoration": None,
            "discriminator": "1656",
            "public_flags": 0,
        },
        "attachments": [],
        "embeds": [],
        "mentions": [],
        "mention_roles": [],
        "pinned": False,
        "mention_everyone": False,
        "tts": False,
        "timestamp": "2021-12-22T11:55:52.822000 00:00",
        "edited_timestamp": None,
        "flags": 0,
        "components": [],
    },
    {
        "id": "923181935247896586",
        "type": 0,
        "content": "ta timezona je asi špatně (a na rozdíl od name to nemůžu upravit)",
        "channel_id": "923161263243165757",
        "author": {
            "id": "652142810291765248",
            "username": "benabraham",
            "avatar": "24a0e0ac4a48be5a9870e4c67c760bb2",
            "avatar_decoration": None,
            "discriminator": "1656",
            "public_flags": 0,
        },
        "attachments": [],
        "embeds": [],
        "mentions": [],
        "mention_roles": [],
        "pinned": False,
        "mention_everyone": False,
        "tts": False,
        "timestamp": "2021-12-22T11:55:25.254000 00:00",
        "edited_timestamp": None,
        "flags": 0,
        "components": [],
    },
    {
        "id": "923181632112955404",
        "type": 0,
        "content": "",
        "channel_id": "923161263243165757",
        "author": {
            "id": "652142810291765248",
            "username": "benabraham",
            "avatar": "24a0e0ac4a48be5a9870e4c67c760bb2",
            "avatar_decoration": None,
            "discriminator": "1656",
            "public_flags": 0,
        },
        "attachments": [
            {
                "id": "923181631924228096",
                "filename": "unknown.png",
                "size": 26714,
                "url": "https://cdn.discordapp.com/attachments/923161263243165757/923181631924228096/unknown.png",
                "proxy_url": "https://media.discordapp.net/attachments/923161263243165757/923181631924228096/unknown.png",
                "width": 759,
                "height": 394,
                "content_type": "image/png",
            }
        ],
        "embeds": [],
        "mentions": [],
        "mention_roles": [],
        "pinned": False,
        "mention_everyone": False,
        "tts": False,
        "timestamp": "2021-12-22T11:54:12.981000 00:00",
        "edited_timestamp": None,
        "flags": 0,
        "components": [],
    },
    {
        "id": "923181620117274624",
        "type": 21,
        "content": "",
        "channel_id": "923161263243165757",
        "author": {
            "id": "652142810291765248",
            "username": "benabraham",
            "avatar": "24a0e0ac4a48be5a9870e4c67c760bb2",
            "avatar_decoration": None,
            "discriminator": "1656",
            "public_flags": 0,
        },
        "attachments": [],
        "embeds": [],
        "mentions": [
            {
                "id": "668226181769986078",
                "username": "honzajavorek",
                "avatar": "f05f801793b03a1bf5fa711cd1830385",
                "avatar_decoration": None,
                "discriminator": "4722",
                "public_flags": 0,
            }
        ],
        "mention_roles": [],
        "pinned": False,
        "mention_everyone": False,
        "tts": False,
        "timestamp": "2021-12-22T11:54:10.121000 00:00",
        "edited_timestamp": None,
        "flags": 0,
        "components": [],
        "message_reference": {
            "channel_id": "789046675247333397",
            "guild_id": "769966886598737931",
            "message_id": "923161263243165757",
        },
        "referenced_message": {
            "id": "923161263243165757",
            "type": 0,
            "content": "Vyrobil jsem ten iCalendar feed, jak ho chtěl <@!652142810291765248> a možná ještě i někdo další  🗓️ Když si to přidáte do svého kalendáře (jako živé URL, nestahovat jako soubor), měly by se vám tam automaticky objevovat JG akce https://junior.guru/api/events.ics Akorát teď není lednová ještě uveřejněná (čekám na detaily od speakera), tak se vám zatím objeví jen přednášky zpětně 😅 Každopádně budu rád, když mi to pomůžete otestovat, kdo to využijete.",
            "channel_id": "789046675247333397",
            "author": {
                "id": "668226181769986078",
                "username": "honzajavorek",
                "avatar": "f05f801793b03a1bf5fa711cd1830385",
                "avatar_decoration": None,
                "discriminator": "4722",
                "public_flags": 0,
            },
            "attachments": [],
            "embeds": [],
            "mentions": [
                {
                    "id": "652142810291765248",
                    "username": "benabraham",
                    "avatar": "24a0e0ac4a48be5a9870e4c67c760bb2",
                    "avatar_decoration": None,
                    "discriminator": "1656",
                    "public_flags": 0,
                }
            ],
            "mention_roles": [],
            "pinned": False,
            "mention_everyone": False,
            "tts": False,
            "timestamp": "2021-12-22T10:33:16.664000 00:00",
            "edited_timestamp": None,
            "flags": 32,
            "components": [],
            "thread": {
                "id": "923161263243165757",
                "guild_id": "769966886598737931",
                "parent_id": "789046675247333397",
                "owner_id": "652142810291765248",
                "type": 10,
                "name": "kalendář",
                "last_message_id": "923188070696767488",
                "thread_metadata": {
                    "archived": True,
                    "archive_timestamp": "2021-12-25T12:27:32.552000 00:00",
                    "auto_archive_duration": 4320,
                    "locked": False,
                },
                "message_count": 6,
                "member_count": 2,
                "rate_limit_per_user": 0,
                "flags": 0,
                "total_message_sent": 6,
            },
        },
    },
]
```

</details>

As you can see, the last message is quite peculiar. I think instantiation of its `referenced_message` causes the crash. The message doesn't have any content and when I craft a jump URL to see it in the Discord UI, it won't show anything, just the thread as a whole, but no highlight. I have no idea what it is and why it's there.

My idea is that perhaps if there is a thread which contains a message which replies to the initial parent message of the thread, this could happen and confuse the following logic in Message?

```python
if ref.channel_id == channel.id:
    chan = channel
else:
    chan, _ = state._get_guild_channel(resolved)
```

I'll call it a day now, without confirming my theory. Let me know if you have some ideas.
What does the last message look like in Discord?
I can't see it:

> when I craft a jump URL to see it in the Discord UI, it won't show anything, just the thread as a whole, but no highlight. I have no idea what it is and why it's there.

This is how the parent message looks like in the news channel:

<img width="759" alt="Screenshot 2022-07-13 at 20 29 38" src="https://user-images.githubusercontent.com/283441/178805431-0e7845e8-c796-4e07-b229-8f582c06a1a7.png">

This is how the whole thread looks like:

<img width="829" alt="Screenshot 2022-07-13 at 20 31 01" src="https://user-images.githubusercontent.com/283441/178805542-0f0dca96-033c-4aab-bf77-d8efdc7b8153.png">


OK so I wrapped the code around `try/except` and only logged the exception to see what are the other channels where this is a problem. It turns out almost all other threads crash on the same problem! In my thread-heavy server, this is not an outlier problem 🤯

I thought I could just skip the problematic threads and upgrade the library, but that's not an option now. It would effectively mean my bot would skip almost (?) all threads.
Would someone be so kind to try the example code from https://github.com/Pycord-Development/pycord/issues/1491#issuecomment-1181815453 with _any_ thread?
I'm running into the same problem with my threads

Resolving patch:
diff --git a/discord/message.py b/discord/message.py
--- a/discord/message.py
+++ b/discord/message.py
@@ -760,7 +760,7 @@ def __init__(
                     if ref.channel_id == channel.id:
                         chan = channel
                     else:
-                        chan, _ = state._get_guild_channel(resolved)
+                        chan, _ = state._get_guild_channel(resolved, guild_id=self.guild.id)
 
                     # the channel will be the correct type here
                     ref.resolved = self.__class__(channel=chan, data=resolved, state=state)  # type: ignore
diff --git a/discord/state.py b/discord/state.py
--- a/discord/state.py
+++ b/discord/state.py
@@ -476,10 +476,10 @@ def _guild_needs_chunking(self, guild: Guild) -> bool:
         # If presences are enabled then we get back the old guild.large behaviour
         return self._chunk_guilds and not guild.chunked and not (self._intents.presences and not guild.large)
 
-    def _get_guild_channel(self, data: MessagePayload) -> Tuple[Union[Channel, Thread], Optional[Guild]]:
+    def _get_guild_channel(self, data: MessagePayload, guild_id: Optional[int] = None) -> Tuple[Union[Channel, Thread], Optional[Guild]]:
         channel_id = int(data["channel_id"])
         try:
-            guild = self._get_guild(int(data["guild_id"]))
+            guild = self._get_guild(int(guild_id or data["guild_id"]))
         except KeyError:
             channel = DMChannel._from_message(self, channel_id)
             guild = None


Test patch: