outside-fetcher/tasks/channel_history.py

63 lines
2.0 KiB
Python
Raw Normal View History

2019-11-03 22:11:45 +01:00
import pyrogram
2019-11-04 16:58:31 +01:00
import typing
2019-11-06 15:53:46 +01:00
from .executors import MtProtoTask
2019-11-05 19:48:14 +01:00
from .webhook import WebHookDataForward
2019-11-06 15:53:46 +01:00
from .reformat import message_to_bot_api
2019-11-03 22:11:45 +01:00
from pyrogram.api.types import ChannelMessagesFilterEmpty
from pyrogram.api.types.updates import ChannelDifference, ChannelDifferenceTooLong, ChannelDifferenceEmpty
from pyrogram.api.functions.updates.get_channel_difference import GetChannelDifference
2019-11-04 15:08:33 +01:00
2019-11-04 16:58:31 +01:00
class ChannelHistoryReadTask(MtProtoTask):
2019-11-06 15:53:46 +01:00
_channel: typing.Union[pyrogram.Chat, str]
2019-11-05 19:48:14 +01:00
_client: pyrogram.Client
_pts: int
_webhook: str
2019-11-04 15:08:33 +01:00
2019-11-06 15:53:46 +01:00
def __init__(self, client: pyrogram.Client, channel: str, webhook: str):
super().__init__()
2019-11-05 19:48:14 +01:00
self._pts = False
self._client = client
self._channel = channel
self._webhook = webhook
2019-11-06 15:53:46 +01:00
async def setup(self):
self._channel = await self._client.resolve_peer(self._channel)
2019-11-05 19:48:14 +01:00
async def process(self) -> typing.Union[bool, int]:
response = await self._client.send(
2019-11-03 22:11:45 +01:00
GetChannelDifference(
2019-11-05 19:48:14 +01:00
channel=self._channel,
2019-11-03 22:11:45 +01:00
filter=ChannelMessagesFilterEmpty(),
2019-11-05 19:48:14 +01:00
pts=self._pts if self._pts else 0xFFFFFFF,
2019-11-03 22:11:45 +01:00
limit=0xFFFFFFF,
force=True
)
)
if isinstance(response, ChannelDifference):
2019-11-05 19:48:14 +01:00
self._pts = response.pts
2019-11-03 22:11:45 +01:00
users = {i.id: i for i in response.users}
chats = {i.id: i for i in response.chats}
for message in response.new_messages:
2019-11-06 15:53:46 +01:00
data = await message_to_bot_api(self._client, users, chats, message)
forwarder = WebHookDataForward(self._webhook, data)
2019-11-05 19:48:14 +01:00
await self.future(forwarder)
2019-11-03 22:11:45 +01:00
if not response.final:
return 1
return response.timeout
if isinstance(response, ChannelDifferenceEmpty):
2019-11-05 19:48:14 +01:00
self._pts = response.pts
2019-11-03 22:11:45 +01:00
return response.timeout
if isinstance(response, ChannelDifferenceTooLong):
return False