thememasterchat 0.1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. pytchat/__init__.py +44 -0
  2. pytchat/api.py +34 -0
  3. pytchat/config/__init__.py +16 -0
  4. pytchat/config/mylogger.py +38 -0
  5. pytchat/core/__init__.py +7 -0
  6. pytchat/core/pytchat.py +229 -0
  7. pytchat/core_async/__init__.py +0 -0
  8. pytchat/core_async/buffer.py +38 -0
  9. pytchat/core_async/livechat.py +374 -0
  10. pytchat/core_multithread/__init__.py +0 -0
  11. pytchat/core_multithread/buffer.py +38 -0
  12. pytchat/core_multithread/livechat.py +358 -0
  13. pytchat/exceptions.py +81 -0
  14. pytchat/paramgen/__init__.py +0 -0
  15. pytchat/paramgen/arcparam.py +44 -0
  16. pytchat/paramgen/enc.py +24 -0
  17. pytchat/paramgen/liveparam.py +70 -0
  18. pytchat/parser/__init__.py +0 -0
  19. pytchat/parser/live.py +122 -0
  20. pytchat/processors/__init__.py +0 -0
  21. pytchat/processors/chat_processor.py +30 -0
  22. pytchat/processors/combinator.py +42 -0
  23. pytchat/processors/compatible/__init__.py +0 -0
  24. pytchat/processors/compatible/processor.py +88 -0
  25. pytchat/processors/compatible/renderer/__init__.py +0 -0
  26. pytchat/processors/compatible/renderer/base.py +82 -0
  27. pytchat/processors/compatible/renderer/currency.py +38 -0
  28. pytchat/processors/compatible/renderer/legacypaid.py +42 -0
  29. pytchat/processors/compatible/renderer/membership.py +40 -0
  30. pytchat/processors/compatible/renderer/paidmessage.py +42 -0
  31. pytchat/processors/compatible/renderer/paidsticker.py +47 -0
  32. pytchat/processors/compatible/renderer/textmessage.py +6 -0
  33. pytchat/processors/default/__init__.py +0 -0
  34. pytchat/processors/default/custom_encoder.py +11 -0
  35. pytchat/processors/default/processor.py +181 -0
  36. pytchat/processors/default/renderer/__init__.py +0 -0
  37. pytchat/processors/default/renderer/base.py +101 -0
  38. pytchat/processors/default/renderer/currency.py +38 -0
  39. pytchat/processors/default/renderer/donation.py +6 -0
  40. pytchat/processors/default/renderer/legacypaid.py +15 -0
  41. pytchat/processors/default/renderer/membership.py +18 -0
  42. pytchat/processors/default/renderer/paidmessage.py +47 -0
  43. pytchat/processors/default/renderer/paidsticker.py +47 -0
  44. pytchat/processors/default/renderer/textmessage.py +6 -0
  45. pytchat/processors/dummy_processor.py +10 -0
  46. pytchat/processors/html_archiver.py +170 -0
  47. pytchat/processors/jsonfile_archiver.py +69 -0
  48. pytchat/processors/simple_display_processor.py +61 -0
  49. pytchat/processors/speed/__init__.py +0 -0
  50. pytchat/processors/speed/calculator.py +186 -0
  51. pytchat/processors/superchat/__init__.py +0 -0
  52. pytchat/processors/superchat/calculator.py +75 -0
  53. pytchat/processors/tsv_archiver.py +67 -0
  54. pytchat/util/__init__.py +195 -0
  55. thememasterchat-0.1.0.1.dist-info/METADATA +212 -0
  56. thememasterchat-0.1.0.1.dist-info/RECORD +59 -0
  57. thememasterchat-0.1.0.1.dist-info/WHEEL +5 -0
  58. thememasterchat-0.1.0.1.dist-info/licenses/LICENSE +23 -0
  59. thememasterchat-0.1.0.1.dist-info/top_level.txt +1 -0
pytchat/__init__.py ADDED
@@ -0,0 +1,44 @@
1
+ """
2
+ pytchat is a lightweight python library to browse youtube livechat without Selenium or BeautifulSoup.
3
+ """
4
+ __copyright__ = 'Copyright (C) 2019, 2020, 2021 taizan-hokuto, revertical, Theme Master'
5
+ __license__ = 'MIT'
6
+ __version__ = '0.1.0.1'
7
+ __author__ = 'Theme Master'
8
+ __url__ = 'https://github.com/ThemeMasterOS/ThemeMasterChat'
9
+
10
+
11
+ from .exceptions import (
12
+ ChatParseException,
13
+ ResponseContextError,
14
+ NoContents,
15
+ NoContinuation,
16
+ IllegalFunctionCall,
17
+ InvalidVideoIdException,
18
+ UnknownConnectionError,
19
+ RetryExceedMaxCount,
20
+ ChatDataFinished,
21
+ ReceivedUnknownContinuation,
22
+ FailedExtractContinuation,
23
+ VideoInfoParseError,
24
+ PatternUnmatchError
25
+ )
26
+
27
+ from .api import (
28
+ config,
29
+ LiveChat,
30
+ LiveChatAsync,
31
+ ChatProcessor,
32
+ CompatibleProcessor,
33
+ DummyProcessor,
34
+ DefaultProcessor,
35
+ HTMLArchiver,
36
+ TSVArchiver,
37
+ JsonfileArchiver,
38
+ SimpleDisplayProcessor,
39
+ SpeedCalculator,
40
+ SuperchatCalculator,
41
+ create
42
+ )
43
+
44
+ # flake8: noqa
pytchat/api.py ADDED
@@ -0,0 +1,34 @@
1
+ from . import config
2
+ from .core import create
3
+ from .core_multithread.livechat import LiveChat
4
+ from .core_async.livechat import LiveChatAsync
5
+ from .processors.chat_processor import ChatProcessor
6
+ from .processors.compatible.processor import CompatibleProcessor
7
+ from .processors.default.processor import DefaultProcessor
8
+ from .processors.dummy_processor import DummyProcessor
9
+ from .processors.html_archiver import HTMLArchiver
10
+ from .processors.tsv_archiver import TSVArchiver
11
+ from .processors.jsonfile_archiver import JsonfileArchiver
12
+ from .processors.simple_display_processor import SimpleDisplayProcessor
13
+ from .processors.speed.calculator import SpeedCalculator
14
+ from .processors.superchat.calculator import SuperchatCalculator
15
+
16
+
17
+ __all__ = [
18
+ config,
19
+ LiveChat,
20
+ LiveChatAsync,
21
+ ChatProcessor,
22
+ CompatibleProcessor,
23
+ DummyProcessor,
24
+ DefaultProcessor,
25
+ HTMLArchiver,
26
+ TSVArchiver,
27
+ JsonfileArchiver,
28
+ SimpleDisplayProcessor,
29
+ SpeedCalculator,
30
+ SuperchatCalculator,
31
+ create
32
+ ]
33
+
34
+ # flake8: noqa
@@ -0,0 +1,16 @@
1
+ import logging # noqa
2
+ from . import mylogger
3
+ from base64 import a85decode as dc
4
+ headers = {
5
+ 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36 Edg/86.0.622.63,gzip(gfe)',
6
+ }
7
+ m_headers = {
8
+ 'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Mobile Safari/537.36 Edg/91.0.864.59',
9
+ }
10
+ _sml = dc(b"BQS?8F#ks-GB\\6`H#IhIF^eo7@rH3;H#IhIF^eor06T''Ch\\'(?XmbXF>%9<FC/iuG%G#jBOQ!ICLqcS5tQB2;gCZ)?UdXC;f$GR3)MM2<(0>O7mh!,G@+K5?SO9T@okV").decode()
11
+ _smr = dc(b"BQS?8F#ks-GB\\6`H#IhIF^eo7@rH3;H#IhIF^eor06T''Ch\\'(?XmbXF>%9<FC/iuG%G#jBOQ!iEb03+@<k(QAU-F)8U=fDGsP557S5F7CiNH7;)D3N77^*B6YU@\\?WfBr0emZX=#^").decode()
12
+
13
+
14
+ def logger(module_name: str, loglevel=None):
15
+ module_logger = mylogger.get_logger(module_name, loglevel=loglevel)
16
+ return module_logger
@@ -0,0 +1,38 @@
1
+ from logging import NullHandler, getLogger, StreamHandler, FileHandler
2
+ import logging
3
+ from datetime import datetime
4
+
5
+
6
+ def get_logger(modname, loglevel=logging.DEBUG):
7
+ logger = getLogger(modname)
8
+ if loglevel is None:
9
+ logger.addHandler(NullHandler())
10
+ return logger
11
+ logger.setLevel(loglevel)
12
+ # create handler1 for showing info
13
+ handler1 = StreamHandler()
14
+ my_formatter = MyFormatter()
15
+ handler1.setFormatter(my_formatter)
16
+
17
+ handler1.setLevel(loglevel)
18
+ logger.addHandler(handler1)
19
+ # create handler2 for recording log file
20
+ if loglevel <= logging.DEBUG:
21
+ handler2 = FileHandler(filename="log.txt", encoding='utf-8')
22
+ handler2.setLevel(logging.ERROR)
23
+ handler2.setFormatter(my_formatter)
24
+
25
+ logger.addHandler(handler2)
26
+ return logger
27
+
28
+
29
+ class MyFormatter(logging.Formatter):
30
+ def format(self, record):
31
+ timestamp = (
32
+ datetime.fromtimestamp(record.created)).strftime("%m-%d %H:%M:%S")
33
+ module = (record.module).ljust(15)
34
+ funcname = (record.funcName).ljust(18)
35
+ lineno = str(record.lineno).rjust(4)
36
+ message = record.getMessage()
37
+
38
+ return timestamp + '| ' + module + ' { ' + funcname + ':' + lineno + '} - ' + message
@@ -0,0 +1,7 @@
1
+ from .pytchat import PytchatCore
2
+ from .. util import extract_video_id
3
+
4
+
5
+ def create(video_id: str, **kwargs):
6
+ _vid = extract_video_id(video_id)
7
+ return PytchatCore(_vid, **kwargs)
@@ -0,0 +1,229 @@
1
+ import httpx
2
+ import json
3
+ import signal
4
+ import time
5
+ import traceback
6
+ from ..parser.live import Parser
7
+ from .. import config
8
+ from .. import exceptions
9
+ from ..paramgen import liveparam, arcparam
10
+ from ..processors.default.processor import DefaultProcessor
11
+ from ..processors.combinator import Combinator
12
+ from .. import util
13
+
14
+ headers = config.headers
15
+ MAX_RETRY = 10
16
+
17
+ class PytchatCore:
18
+ '''
19
+
20
+ core pytchat object
21
+
22
+ Parameter
23
+ ---------
24
+ video_id : str
25
+
26
+ seektime : int
27
+ start position of fetching chat (seconds).
28
+ This option is valid for archived chat only.
29
+ If negative value, chat data posted before the start of the broadcast
30
+ will be retrieved as well.
31
+
32
+ processor : ChatProcessor
33
+
34
+ client : httpx.Client
35
+ The client for connecting youtube.
36
+ You can specify any customized httpx client (e.g. coolies, user agent).
37
+
38
+ interruptable : bool
39
+ Allows keyboard interrupts.
40
+ Set this parameter to False if your own multi-threading program causes
41
+ the problem.
42
+
43
+ force_replay : bool
44
+ force to fetch archived chat data, even if specified video is live.
45
+
46
+ topchat_only : bool
47
+ If True, get only top chat.
48
+
49
+ hold_exception : bool [default:True]
50
+ If True, when exceptions occur, the exception is held internally,
51
+ and can be raised by raise_for_status().
52
+
53
+ replay_continuation : str
54
+ If this parameter is not None, the processor will attempt to get chat data from continuation.
55
+ This parameter is only allowed in archived mode.
56
+
57
+ Attributes
58
+ ---------
59
+ _is_alive : bool
60
+ Flag to stop getting chat.
61
+ '''
62
+
63
+ def __init__(self, video_id,
64
+ seektime=-1,
65
+ processor=None,
66
+ client=None,
67
+ interruptable=True,
68
+ force_replay=False,
69
+ topchat_only=False,
70
+ hold_exception=True,
71
+ logger=config.logger(__name__),
72
+ replay_continuation=None
73
+ ):
74
+ self._client = client
75
+ if client is None:
76
+ self._client = httpx.Client(http2=True)
77
+
78
+ if processor is None:
79
+ processor = DefaultProcessor()
80
+ self._video_id = util.extract_video_id(video_id)
81
+ self.seektime = seektime
82
+ if isinstance(processor, tuple):
83
+ self.processor = Combinator(processor)
84
+ else:
85
+ self.processor = processor
86
+ self._is_alive = True
87
+ self._is_replay = force_replay or (replay_continuation is not None)
88
+ self._hold_exception = hold_exception
89
+ self._exception_holder = None
90
+ self._parser = Parser(
91
+ is_replay=self._is_replay,
92
+ exception_holder=self._exception_holder
93
+ )
94
+ self._first_fetch = replay_continuation is None
95
+ self._fetch_url = config._sml if replay_continuation is None else config._smr
96
+ self._topchat_only = topchat_only
97
+ self._dat = ''
98
+ self._last_offset_ms = 0
99
+ self._logger = logger
100
+ self.continuation = replay_continuation
101
+ if interruptable:
102
+ signal.signal(signal.SIGINT, lambda a, b: self.terminate())
103
+ self._setup()
104
+
105
+ def _setup(self):
106
+ if not self.continuation:
107
+ time.sleep(0.1) # sleep shortly to prohibit skipping fetching data
108
+ """Fetch first continuation parameter,
109
+ create and start _listen loop.
110
+ """
111
+ self.continuation = liveparam.getparam(
112
+ self._video_id,
113
+ channel_id=util.get_channelid(self._client, self._video_id),
114
+ past_sec=3)
115
+
116
+ def _get_chat_component(self):
117
+ ''' Fetch chat data and store them into buffer,
118
+ get next continuaiton parameter and loop.
119
+
120
+ Parameter
121
+ ---------
122
+ continuation : str
123
+ parameter for next chat data
124
+ '''
125
+ try:
126
+ if self.continuation and self._is_alive:
127
+ contents = self._get_contents(self.continuation, self._client, headers)
128
+ metadata, chatdata = self._parser.parse(contents)
129
+ timeout = metadata['timeoutMs'] / 1000
130
+ chat_component = {
131
+ "video_id": self._video_id,
132
+ "timeout": timeout,
133
+ "chatdata": chatdata
134
+ }
135
+ self.continuation = metadata.get('continuation')
136
+ self._last_offset_ms = metadata.get('last_offset_ms', 0)
137
+ return chat_component
138
+ except exceptions.ChatParseException as e:
139
+ self._logger.debug(f"[{self._video_id}]{str(e)}")
140
+ self._raise_exception(e)
141
+ except Exception as e:
142
+ self._logger.error(f"{traceback.format_exc(limit=-1)}")
143
+ self._raise_exception(e)
144
+
145
+ def _get_contents(self, continuation, client, headers):
146
+ '''Get 'continuationContents' from livechat json.
147
+ If contents is None at first fetching,
148
+ try to fetch archive chat data.
149
+
150
+ Return:
151
+ -------
152
+ 'continuationContents' which includes metadata & chat data.
153
+ '''
154
+ livechat_json = self._get_livechat_json(
155
+ continuation, client, replay=self._is_replay, offset_ms=self._last_offset_ms)
156
+ contents, dat = self._parser.get_contents(livechat_json)
157
+ if self._dat == '' and dat:
158
+ self._dat = dat
159
+ if self._first_fetch:
160
+ if contents is None or self._is_replay:
161
+ '''Try to fetch archive chat data.'''
162
+ self._parser.is_replay = True
163
+ self._fetch_url = config._smr
164
+ continuation = arcparam.getparam(
165
+ self._video_id, self.seektime, self._topchat_only, util.get_channelid(client, self._video_id))
166
+ livechat_json = self._get_livechat_json(
167
+ continuation, client, replay=True, offset_ms=self.seektime * 1000)
168
+ reload_continuation = self._parser.reload_continuation(
169
+ self._parser.get_contents(livechat_json)[0])
170
+ if reload_continuation:
171
+ livechat_json = (self._get_livechat_json(reload_continuation, client, replay=True, offset_ms=0))
172
+ contents, _ = self._parser.get_contents(livechat_json)
173
+ self._is_replay = True
174
+ self._first_fetch = False
175
+ return contents
176
+
177
+ def _get_livechat_json(self, continuation, client, replay: bool, offset_ms: int = 0):
178
+ '''
179
+ Get json which includes chat data.
180
+ '''
181
+ livechat_json = None
182
+ err = None
183
+ if offset_ms < 0:
184
+ offset_ms = 0
185
+ param = util.get_param(continuation, dat=self._dat, replay=replay, offsetms=offset_ms)
186
+ for _ in range(MAX_RETRY + 1):
187
+ try:
188
+ response = client.post(self._fetch_url, json=param)
189
+ livechat_json = response.json()
190
+ break
191
+ except (json.JSONDecodeError, httpx.ConnectTimeout, httpx.ReadTimeout, httpx.ConnectError,
192
+ httpx.ReadError, httpx.RemoteProtocolError, httpx.LocalProtocolError) as e:
193
+ err = e
194
+ time.sleep(2)
195
+ continue
196
+ else:
197
+ self._logger.error(f"[{self._video_id}]"
198
+ f"Exceeded retry count. Last error: {str(err)}")
199
+ self._raise_exception(exceptions.RetryExceedMaxCount())
200
+ return livechat_json
201
+
202
+ def get(self):
203
+ if self.is_alive():
204
+ chat_component = self._get_chat_component()
205
+ return self.processor.process([chat_component])
206
+ else:
207
+ return []
208
+
209
+ def is_replay(self):
210
+ return self._is_replay
211
+
212
+ def is_alive(self):
213
+ return self._is_alive
214
+
215
+ def terminate(self):
216
+ if not self.is_alive():
217
+ return
218
+ self._is_alive = False
219
+ self.processor.finalize()
220
+
221
+ def raise_for_status(self):
222
+ if self._exception_holder is not None:
223
+ raise self._exception_holder
224
+
225
+ def _raise_exception(self, exception: Exception = None):
226
+ self.terminate()
227
+ if self._hold_exception is False:
228
+ raise exception
229
+ self._exception_holder = exception
File without changes
@@ -0,0 +1,38 @@
1
+
2
+ import asyncio
3
+
4
+
5
+ class Buffer(asyncio.Queue):
6
+ '''
7
+ Buffer for storing chat data.
8
+
9
+ Parameter
10
+ ---------
11
+ maxsize : int
12
+ Maximum number of chat blocks to be stored.
13
+ If it exceeds the maximum, the oldest chat block will be discarded.
14
+ '''
15
+
16
+ def __init__(self, maxsize=0):
17
+ super().__init__(maxsize)
18
+
19
+ async def put(self, item):
20
+ if item is None:
21
+ return
22
+ if super().full():
23
+ super().get_nowait()
24
+ await super().put(item)
25
+
26
+ def put_nowait(self, item):
27
+ if item is None:
28
+ return
29
+ if super().full():
30
+ super().get_nowait()
31
+ super().put_nowait(item)
32
+
33
+ async def get(self):
34
+ ret = []
35
+ ret.append(await super().get())
36
+ while not super().empty():
37
+ ret.append(super().get_nowait())
38
+ return ret