From 2474207691c3482bb018aeae60559dde293f68ef Mon Sep 17 00:00:00 2001 From: taizan-hokuto <55448286+taizan-hokuto@users.noreply.github.com> Date: Thu, 4 Jun 2020 23:10:26 +0900 Subject: [PATCH] Format code --- pytchat/__init__.py | 4 +- pytchat/api.py | 2 + pytchat/cli/__init__.py | 36 ++--- pytchat/cli/arguments.py | 13 +- pytchat/cli/singleton.py | 6 +- pytchat/config/__init__.py | 10 +- pytchat/config/mylogger.py | 18 +-- pytchat/core_async/buffer.py | 17 ++- pytchat/core_async/livechat.py | 7 +- pytchat/core_multithread/buffer.py | 20 +-- pytchat/core_multithread/livechat.py | 4 +- pytchat/exceptions.py | 11 +- pytchat/paramgen/arcparam.py | 2 +- pytchat/paramgen/arcparam_mining.py | 36 ++--- pytchat/paramgen/liveparam.py | 6 +- pytchat/parser/live.py | 14 +- pytchat/processors/chat_processor.py | 10 +- pytchat/processors/combinator.py | 11 +- pytchat/processors/compatible/processor.py | 6 +- .../processors/compatible/renderer/base.py | 68 +++++----- .../compatible/renderer/currency.py | 2 +- .../compatible/renderer/legacypaid.py | 45 +++---- .../compatible/renderer/membership.py | 6 +- .../compatible/renderer/paidmessage.py | 33 ++--- .../compatible/renderer/paidsticker.py | 37 +++-- .../compatible/renderer/textmessage.py | 2 + pytchat/processors/default/processor.py | 6 +- pytchat/processors/default/renderer/base.py | 64 +++++---- .../processors/default/renderer/currency.py | 2 +- .../processors/default/renderer/legacypaid.py | 13 +- .../processors/default/renderer/membership.py | 4 +- .../default/renderer/paidmessage.py | 19 ++- .../default/renderer/paidsticker.py | 22 ++- .../default/renderer/textmessage.py | 2 + pytchat/processors/dummy_processor.py | 2 + pytchat/processors/html_archiver.py | 45 +++---- pytchat/processors/jsonfile_archiver.py | 49 +++---- .../processors/simple_display_processor.py | 54 ++++---- pytchat/processors/speed/calculator.py | 102 +++++++------- pytchat/processors/superchat/calculator.py | 21 +-- pytchat/processors/tsv_archiver.py | 25 ++-- pytchat/tool/extract/asyncdl.py | 85 ++++++------ pytchat/tool/extract/block.py | 25 ++-- pytchat/tool/extract/duplcheck.py | 127 +++++++++--------- pytchat/tool/extract/extractor.py | 33 ++--- pytchat/tool/extract/parser.py | 24 ++-- pytchat/tool/extract/patch.py | 35 ++--- pytchat/tool/extract/worker.py | 32 ++--- pytchat/tool/videoinfo.py | 25 ++-- pytchat/util/__init__.py | 15 ++- 50 files changed, 635 insertions(+), 622 deletions(-) diff --git a/pytchat/__init__.py b/pytchat/__init__.py index 7c0b474..86bf198 100644 --- a/pytchat/__init__.py +++ b/pytchat/__init__.py @@ -27,4 +27,6 @@ from .api import ( SpeedCalculator, SuperchatCalculator, VideoInfo -) \ No newline at end of file +) + +# flake8: noqa \ No newline at end of file diff --git a/pytchat/api.py b/pytchat/api.py index ceb4da2..7c67436 100644 --- a/pytchat/api.py +++ b/pytchat/api.py @@ -14,3 +14,5 @@ from .processors.speed.calculator import SpeedCalculator from .processors.superchat.calculator import SuperchatCalculator from .tool.extract.extractor import Extractor from .tool.videoinfo import VideoInfo + +# flake8: noqa \ No newline at end of file diff --git a/pytchat/cli/__init__.py b/pytchat/cli/__init__.py index c3c16ac..060b4eb 100644 --- a/pytchat/cli/__init__.py +++ b/pytchat/cli/__init__.py @@ -1,33 +1,31 @@ import argparse -import os from pathlib import Path -from typing import List, Callable from .arguments import Arguments - from .. exceptions import InvalidVideoIdException, NoContentsException -from .. processors.tsv_archiver import TSVArchiver from .. processors.html_archiver import HTMLArchiver from .. tool.extract.extractor import Extractor from .. tool.videoinfo import VideoInfo from .. import __version__ ''' -Most of CLI modules refer to +Most of CLI modules refer to Petter Kraabøl's Twitch-Chat-Downloader https://github.com/PetterKraabol/Twitch-Chat-Downloader (MIT License) ''' + + def main(): - # Arguments + # Arguments parser = argparse.ArgumentParser(description=f'pytchat v{__version__}') parser.add_argument('-v', f'--{Arguments.Name.VIDEO}', type=str, - help='Video IDs separated by commas without space.\n' - 'If ID starts with a hyphen (-), enclose the ID in square brackets.') + help='Video IDs separated by commas without space.\n' + 'If ID starts with a hyphen (-), enclose the ID in square brackets.') parser.add_argument('-o', f'--{Arguments.Name.OUTPUT}', type=str, - help='Output directory (end with "/"). default="./"', default='./') + help='Output directory (end with "/"). default="./"', default='./') parser.add_argument(f'--{Arguments.Name.VERSION}', action='store_true', - help='Settings version') + help='Settings version') Arguments(parser.parse_args().__dict__) if Arguments().print_version: print(f'pytchat v{__version__}') @@ -37,24 +35,26 @@ def main(): if Arguments().video_ids: for video_id in Arguments().video_ids: if '[' in video_id: - video_id = video_id.replace('[','').replace(']','') + video_id = video_id.replace('[', '').replace(']', '') try: info = VideoInfo(video_id) print(f"Extracting...\n" f" video_id: {video_id}\n" f" channel: {info.get_channel_name()}\n" f" title: {info.get_title()}") - path = Path(Arguments().output+video_id+'.html') + path = Path(Arguments().output + video_id + '.html') print(f"output path: {path.resolve()}") - Extractor(video_id, - processor = HTMLArchiver(Arguments().output+video_id+'.html'), - callback = _disp_progress - ).extract() + Extractor(video_id, + processor=HTMLArchiver( + Arguments().output + video_id + '.html'), + callback=_disp_progress + ).extract() print("\nExtraction end.\n") except (InvalidVideoIdException, NoContentsException) as e: print(e) return parser.print_help() -def _disp_progress(a,b): - print('.',end="",flush=True) + +def _disp_progress(a, b): + print('.', end="", flush=True) diff --git a/pytchat/cli/arguments.py b/pytchat/cli/arguments.py index ab3f355..d6fea2b 100644 --- a/pytchat/cli/arguments.py +++ b/pytchat/cli/arguments.py @@ -2,12 +2,13 @@ from typing import Optional, Dict, Union, List from .singleton import Singleton ''' -This modules refer to +This modules refer to Petter Kraabøl's Twitch-Chat-Downloader https://github.com/PetterKraabol/Twitch-Chat-Downloader (MIT License) ''' + class Arguments(metaclass=Singleton): """ Arguments singleton @@ -18,11 +19,11 @@ class Arguments(metaclass=Singleton): OUTPUT: str = 'output' VIDEO: str = 'video' - def __init__(self, - arguments: Optional[Dict[str, Union[str, bool, int]]] = None): + def __init__(self, + arguments: Optional[Dict[str, Union[str, bool, int]]] = None): """ Initialize arguments - :param arguments: Arguments from cli + :param arguments: Arguments from cli (Optional to call singleton instance without parameters) """ @@ -35,5 +36,5 @@ class Arguments(metaclass=Singleton): self.video_ids: List[int] = [] # Videos if arguments[Arguments.Name.VIDEO]: - self.video_ids = [video_id - for video_id in arguments[Arguments.Name.VIDEO].split(',')] + self.video_ids = [video_id + for video_id in arguments[Arguments.Name.VIDEO].split(',')] diff --git a/pytchat/cli/singleton.py b/pytchat/cli/singleton.py index fdf1c2c..53a76f0 100644 --- a/pytchat/cli/singleton.py +++ b/pytchat/cli/singleton.py @@ -1,9 +1,11 @@ ''' -This modules refer to +This modules refer to Petter Kraabøl's Twitch-Chat-Downloader https://github.com/PetterKraabol/Twitch-Chat-Downloader (MIT License) ''' + + class Singleton(type): """ Abstract class for singletons @@ -16,4 +18,4 @@ class Singleton(type): return cls._instances[cls] def get_instance(cls, *args, **kwargs): - cls.__call__(*args, **kwargs) \ No newline at end of file + cls.__call__(*args, **kwargs) diff --git a/pytchat/config/__init__.py b/pytchat/config/__init__.py index a36d2b0..e24eb3f 100644 --- a/pytchat/config/__init__.py +++ b/pytchat/config/__init__.py @@ -1,11 +1,9 @@ -import logging from . import mylogger headers = { - 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'} + 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'} -def logger(module_name: str, loglevel = None): - module_logger = mylogger.get_logger(module_name, loglevel = loglevel) + +def logger(module_name: str, loglevel=None): + module_logger = mylogger.get_logger(module_name, loglevel=loglevel) return module_logger - - diff --git a/pytchat/config/mylogger.py b/pytchat/config/mylogger.py index 3df3fb6..d61e40a 100644 --- a/pytchat/config/mylogger.py +++ b/pytchat/config/mylogger.py @@ -1,31 +1,31 @@ -from logging import NullHandler, getLogger, StreamHandler, FileHandler, Formatter +from logging import NullHandler, getLogger, StreamHandler, FileHandler import logging from datetime import datetime -def get_logger(modname,loglevel=logging.DEBUG): +def get_logger(modname, loglevel=logging.DEBUG): logger = getLogger(modname) - if loglevel == None: + if loglevel is None: logger.addHandler(NullHandler()) return logger logger.setLevel(loglevel) - #create handler1 for showing info + # create handler1 for showing info handler1 = StreamHandler() - my_formatter = MyFormatter() + my_formatter = MyFormatter() handler1.setFormatter(my_formatter) - handler1.setLevel(loglevel) + handler1.setLevel(loglevel) logger.addHandler(handler1) - #create handler2 for recording log file + # create handler2 for recording log file if loglevel <= logging.DEBUG: handler2 = FileHandler(filename="log.txt", encoding='utf-8') handler2.setLevel(logging.ERROR) handler2.setFormatter(my_formatter) - logger.addHandler(handler2) return logger + class MyFormatter(logging.Formatter): def format(self, record): timestamp = ( @@ -35,4 +35,4 @@ class MyFormatter(logging.Formatter): lineno = str(record.lineno).rjust(4) message = record.getMessage() - return timestamp+'| '+module+' { '+funcname+':'+lineno+'} - '+message + return timestamp + '| ' + module + ' { ' + funcname + ':' + lineno + '} - ' + message diff --git a/pytchat/core_async/buffer.py b/pytchat/core_async/buffer.py index e93357e..9fbaac9 100644 --- a/pytchat/core_async/buffer.py +++ b/pytchat/core_async/buffer.py @@ -1,5 +1,7 @@ import asyncio + + class Buffer(asyncio.Queue): ''' チャットデータを格納するバッファの役割を持つFIFOキュー @@ -10,19 +12,20 @@ class Buffer(asyncio.Queue): 格納するチャットブロックの最大個数。0の場合は無限。 最大値を超える場合は古いチャットブロックから破棄される。 ''' - def __init__(self,maxsize = 0): + + def __init__(self, maxsize=0): super().__init__(maxsize) - - async def put(self,item): + + async def put(self, item): if item is None: - return + return if super().full(): super().get_nowait() await super().put(item) - def put_nowait(self,item): + def put_nowait(self, item): if item is None: - return + return if super().full(): super().get_nowait() super().put_nowait(item) @@ -32,4 +35,4 @@ class Buffer(asyncio.Queue): ret.append(await super().get()) while not super().empty(): ret.append(super().get_nowait()) - return ret \ No newline at end of file + return ret diff --git a/pytchat/core_async/livechat.py b/pytchat/core_async/livechat.py index 29ae9d7..1853025 100644 --- a/pytchat/core_async/livechat.py +++ b/pytchat/core_async/livechat.py @@ -169,7 +169,7 @@ class LiveChatAsync: continuation, session, headers) metadata, chatdata = self._parser.parse(contents) - timeout = metadata['timeoutMs']/1000 + timeout = metadata['timeoutMs'] / 1000 chat_component = { "video_id": self.video_id, "timeout": timeout, @@ -177,14 +177,15 @@ class LiveChatAsync: } time_mark = time.time() if self._direct_mode: - processed_chat = self.processor.process([chat_component]) + processed_chat = self.processor.process( + [chat_component]) if isinstance(processed_chat, tuple): await self._callback(*processed_chat) else: await self._callback(processed_chat) else: await self._buffer.put(chat_component) - diff_time = timeout - (time.time()-time_mark) + diff_time = timeout - (time.time() - time_mark) await asyncio.sleep(diff_time) continuation = metadata.get('continuation') except ChatParseException as e: diff --git a/pytchat/core_multithread/buffer.py b/pytchat/core_multithread/buffer.py index 3898572..966f2e9 100644 --- a/pytchat/core_multithread/buffer.py +++ b/pytchat/core_multithread/buffer.py @@ -1,6 +1,7 @@ import queue + class Buffer(queue.Queue): ''' チャットデータを格納するバッファの役割を持つFIFOキュー @@ -11,28 +12,29 @@ class Buffer(queue.Queue): 格納するチャットブロックの最大個数。0の場合は無限。 最大値を超える場合は古いチャットブロックから破棄される。 ''' - def __init__(self,maxsize = 0): + + def __init__(self, maxsize=0): super().__init__(maxsize=maxsize) - - def put(self,item): + + def put(self, item): if item is None: - return + return if super().full(): super().get_nowait() else: super().put(item) - - def put_nowait(self,item): + + def put_nowait(self, item): if item is None: - return + return if super().full(): super().get_nowait() else: super().put_nowait(item) - + def get(self): ret = [] ret.append(super().get()) while not super().empty(): ret.append(super().get()) - return ret \ No newline at end of file + return ret diff --git a/pytchat/core_multithread/livechat.py b/pytchat/core_multithread/livechat.py index 5003331..c1aa0ad 100644 --- a/pytchat/core_multithread/livechat.py +++ b/pytchat/core_multithread/livechat.py @@ -156,7 +156,7 @@ class LiveChat: continuation, session, headers) metadata, chatdata = self._parser.parse(contents) - timeout = metadata['timeoutMs']/1000 + timeout = metadata['timeoutMs'] / 1000 chat_component = { "video_id": self.video_id, "timeout": timeout, @@ -172,7 +172,7 @@ class LiveChat: self._callback(processed_chat) else: self._buffer.put(chat_component) - diff_time = timeout - (time.time()-time_mark) + diff_time = timeout - (time.time() - time_mark) time.sleep(diff_time if diff_time > 0 else 0) continuation = metadata.get('continuation') except ChatParseException as e: diff --git a/pytchat/exceptions.py b/pytchat/exceptions.py index 11e5ba1..1f45829 100644 --- a/pytchat/exceptions.py +++ b/pytchat/exceptions.py @@ -4,18 +4,21 @@ class ChatParseException(Exception): ''' pass + class NoYtinitialdataException(ChatParseException): ''' Thrown when the video is not found. ''' pass + class ResponseContextError(ChatParseException): ''' Thrown when chat data is invalid. ''' pass + class NoLivechatRendererException(ChatParseException): ''' Thrown when livechatRenderer is missing in JSON. @@ -29,24 +32,28 @@ class NoContentsException(ChatParseException): ''' pass + class NoContinuationsException(ChatParseException): ''' Thrown when continuation is missing in ContinuationContents. ''' pass + class IllegalFunctionCall(Exception): ''' - Thrown when get () is called even though + Thrown when get () is called even though set_callback () has been executed. ''' pass + class InvalidVideoIdException(Exception): ''' Thrown when the video_id is not exist (VideoInfo). ''' pass + class UnknownConnectionError(Exception): - pass \ No newline at end of file + pass diff --git a/pytchat/paramgen/arcparam.py b/pytchat/paramgen/arcparam.py index a8048d5..c5f7e07 100644 --- a/pytchat/paramgen/arcparam.py +++ b/pytchat/paramgen/arcparam.py @@ -32,7 +32,7 @@ def _build(video_id, seektime, topchat_only) -> str: elif seektime == 0: timestamp = 1 else: - timestamp = int(seektime*1000000) + timestamp = int(seektime * 1000000) continuation = Continuation() entity = continuation.entity entity.header = _gen_vid(video_id) diff --git a/pytchat/paramgen/arcparam_mining.py b/pytchat/paramgen/arcparam_mining.py index d24deed..7e3525a 100644 --- a/pytchat/paramgen/arcparam_mining.py +++ b/pytchat/paramgen/arcparam_mining.py @@ -36,9 +36,10 @@ def _gen_vid_long(video_id): ] return urllib.parse.quote( - b64enc(reduce(lambda x, y: x+y, item)).decode() + b64enc(reduce(lambda x, y: x + y, item)).decode() ).encode() + def _gen_vid(video_id): """generate video_id parameter. Parameter @@ -50,7 +51,7 @@ def _gen_vid(video_id): bytes : base64 encoded video_id parameter. """ header_magic = b'\x0A\x0F\x1A\x0D\x0A' - header_id = video_id.encode() + header_id = video_id.encode() header_terminator = b'\x20\x01' item = [ @@ -61,9 +62,10 @@ def _gen_vid(video_id): ] return urllib.parse.quote( - b64enc(reduce(lambda x, y: x+y, item)).decode() + b64enc(reduce(lambda x, y: x + y, item)).decode() ).encode() + def _nval(val): """convert value to byte array""" if val < 0: @@ -84,19 +86,19 @@ def _build(video_id, seektime, topchat_only): if seektime == 0: times = b'' else: - times = _nval(int(seektime*1000)) + times = _nval(int(seektime * 1000)) if seektime > 0: - _len_time = b'\x5A' + (len(times)+1).to_bytes(1, 'big') + b'\x10' + _len_time = b'\x5A' + (len(times) + 1).to_bytes(1, 'big') + b'\x10' else: _len_time = b'' - + header_magic = b'\xA2\x9D\xB0\xD3\x04' - sep_0 = b'\x1A' - vid = _gen_vid(video_id) - _tag = b'\x40\x01' - timestamp1 = times - sep_1 = b'\x60\x04\x72\x02\x08' - terminator = b'\x78\x01' + sep_0 = b'\x1A' + vid = _gen_vid(video_id) + _tag = b'\x40\x01' + timestamp1 = times + sep_1 = b'\x60\x04\x72\x02\x08' + terminator = b'\x78\x01' body = [ sep_0, @@ -110,14 +112,12 @@ def _build(video_id, seektime, topchat_only): terminator ] - body = reduce(lambda x, y: x+y, body) + body = reduce(lambda x, y: x + y, body) return urllib.parse.quote( - b64enc(header_magic + - _nval(len(body)) + - body - ).decode() - ) + b64enc(header_magic + _nval(len(body)) + body + ).decode() + ) def getparam(video_id, seektime=0.0, topchat_only=False): diff --git a/pytchat/paramgen/liveparam.py b/pytchat/paramgen/liveparam.py index e0525fa..717443f 100644 --- a/pytchat/paramgen/liveparam.py +++ b/pytchat/paramgen/liveparam.py @@ -68,12 +68,12 @@ def _build(video_id, ts1, ts2, ts3, ts4, ts5, topchat_only) -> str: def _times(past_sec): n = int(time.time()) - _ts1 = n - random.uniform(0, 1*3) + _ts1 = n - random.uniform(0, 1 * 3) _ts2 = n - random.uniform(0.01, 0.99) _ts3 = n - past_sec + random.uniform(0, 1) - _ts4 = n - random.uniform(10*60, 60*60) + _ts4 = n - random.uniform(10 * 60, 60 * 60) _ts5 = n - random.uniform(0.01, 0.99) - return list(map(lambda x: int(x*1000000), [_ts1, _ts2, _ts3, _ts4, _ts5])) + return list(map(lambda x: int(x * 1000000), [_ts1, _ts2, _ts3, _ts4, _ts5])) def getparam(video_id, past_sec=0, topchat_only=False) -> str: diff --git a/pytchat/parser/live.py b/pytchat/parser/live.py index aa30562..5fd6bdb 100644 --- a/pytchat/parser/live.py +++ b/pytchat/parser/live.py @@ -22,7 +22,8 @@ class Parser: if jsn is None: raise ChatParseException('Called with none JSON object.') if jsn['response']['responseContext'].get('errors'): - raise ResponseContextError('The video_id would be wrong, or video is deleted or private.') + raise ResponseContextError( + 'The video_id would be wrong, or video is deleted or private.') contents = jsn['response'].get('continuationContents') return contents @@ -50,17 +51,18 @@ class Parser: cont = contents['liveChatContinuation']['continuations'][0] if cont is None: raise NoContinuationsException('No Continuation') - metadata = (cont.get('invalidationContinuationData') or - cont.get('timedContinuationData') or - cont.get('reloadContinuationData') or - cont.get('liveChatReplayContinuationData') + metadata = (cont.get('invalidationContinuationData') + or cont.get('timedContinuationData') + or cont.get('reloadContinuationData') + or cont.get('liveChatReplayContinuationData') ) if metadata is None: if cont.get("playerSeekContinuationData"): raise ChatParseException('Finished chat data') unknown = list(cont.keys())[0] if unknown: - raise ChatParseException(f"Received unknown continuation type:{unknown}") + raise ChatParseException( + f"Received unknown continuation type:{unknown}") else: raise ChatParseException('Cannot extract continuation data') return self._create_data(metadata, contents) diff --git a/pytchat/processors/chat_processor.py b/pytchat/processors/chat_processor.py index 6e62114..98d2227 100644 --- a/pytchat/processors/chat_processor.py +++ b/pytchat/processors/chat_processor.py @@ -3,11 +3,12 @@ class ChatProcessor: Abstract class that processes chat data. Receive chat data (actions) from Listener. ''' + def process(self, chat_components: list): ''' Interface that represents processing of chat data. - Called from LiveChat object. - + Called from LiveChat object. + Parameter ---------- chat_components: List[component] @@ -20,8 +21,3 @@ class ChatProcessor: } ''' pass - - - - - diff --git a/pytchat/processors/combinator.py b/pytchat/processors/combinator.py index c3a81b7..7784418 100644 --- a/pytchat/processors/combinator.py +++ b/pytchat/processors/combinator.py @@ -1,5 +1,6 @@ from .chat_processor import ChatProcessor + class Combinator(ChatProcessor): ''' Combinator combines multiple chat processors. @@ -8,11 +9,11 @@ class Combinator(ChatProcessor): For example: [constructor] chat = LiveChat("video_id", processor = ( Processor1(), Processor2(), Processor3() ) ) - + [receive return values] ret1, ret2, ret3 = chat.get() - - The return values are tuple of processed chat data, + + The return values are tuple of processed chat data, the order of return depends on parameter order. Parameter @@ -34,6 +35,4 @@ class Combinator(ChatProcessor): Tuple of chat data processed by each chat processor. ''' return tuple(processor.process(chat_components) - for processor in self.processors) - - + for processor in self.processors) diff --git a/pytchat/processors/compatible/processor.py b/pytchat/processors/compatible/processor.py index 23c5ef0..6b443e0 100644 --- a/pytchat/processors/compatible/processor.py +++ b/pytchat/processors/compatible/processor.py @@ -1,5 +1,3 @@ -import datetime -import time from .renderer.textmessage import LiveChatTextMessageRenderer from .renderer.paidmessage import LiveChatPaidMessageRenderer from .renderer.paidsticker import LiveChatPaidStickerRenderer @@ -39,7 +37,7 @@ class CompatibleProcessor(ChatProcessor): chat = self.parse(action) if chat: chatlist.append(chat) - ret["pollingIntervalMillis"] = int(timeout*1000) + ret["pollingIntervalMillis"] = int(timeout * 1000) ret["pageInfo"] = { "totalResults": len(chatlist), "resultsPerPage": len(chatlist), @@ -58,7 +56,7 @@ class CompatibleProcessor(ChatProcessor): rd = {} try: renderer = self.get_renderer(item) - if renderer == None: + if renderer is None: return None rd["kind"] = "youtube#liveChatMessage" diff --git a/pytchat/processors/compatible/renderer/base.py b/pytchat/processors/compatible/renderer/base.py index d9003f9..248a93a 100644 --- a/pytchat/processors/compatible/renderer/base.py +++ b/pytchat/processors/compatible/renderer/base.py @@ -1,68 +1,67 @@ -import datetime, pytz +import datetime +import pytz + class BaseRenderer: def __init__(self, item, chattype): self.renderer = list(item.values())[0] self.chattype = chattype - def get_snippet(self): message = self.get_message(self.renderer) return { - "type" : self.chattype, - "liveChatId" : "", - "authorChannelId" : self.renderer.get("authorExternalChannelId"), - "publishedAt" : self.get_publishedat(self.renderer.get("timestampUsec",0)), - "hasDisplayContent" : True, - "displayMessage" : message, + "type": self.chattype, + "liveChatId": "", + "authorChannelId": self.renderer.get("authorExternalChannelId"), + "publishedAt": self.get_publishedat(self.renderer.get("timestampUsec", 0)), + "hasDisplayContent": True, + "displayMessage": message, "textMessageDetails": { - "messageText" : message + "messageText": message } } - def get_authordetails(self): authorExternalChannelId = self.renderer.get("authorExternalChannelId") - #parse subscriber type + # parse subscriber type isVerified, isChatOwner, isChatSponsor, isChatModerator = ( self.get_badges(self.renderer) ) - return { - "channelId" : authorExternalChannelId, - "channelUrl" : "http://www.youtube.com/channel/"+authorExternalChannelId, - "displayName" : self.renderer["authorName"]["simpleText"], - "profileImageUrl" : self.renderer["authorPhoto"]["thumbnails"][1]["url"] , - "isVerified" : isVerified, - "isChatOwner" : isChatOwner, - "isChatSponsor" : isChatSponsor, - "isChatModerator" : isChatModerator - } + return { + "channelId": authorExternalChannelId, + "channelUrl": "http://www.youtube.com/channel/" + authorExternalChannelId, + "displayName": self.renderer["authorName"]["simpleText"], + "profileImageUrl": self.renderer["authorPhoto"]["thumbnails"][1]["url"], + "isVerified": isVerified, + "isChatOwner": isChatOwner, + "isChatSponsor": isChatSponsor, + "isChatModerator": isChatModerator + } - - def get_message(self,renderer): + def get_message(self, renderer): message = '' if renderer.get("message"): - runs=renderer["message"].get("runs") + runs = renderer["message"].get("runs") if runs: for r in runs: if r: if r.get('emoji'): - message += r['emoji'].get('shortcuts',[''])[0] + message += r['emoji'].get('shortcuts', [''])[0] else: - message += r.get('text','') + message += r.get('text', '') return message - def get_badges(self,renderer): + def get_badges(self, renderer): isVerified = False isChatOwner = False isChatSponsor = False isChatModerator = False - badges=renderer.get("authorBadges") + badges = renderer.get("authorBadges") if badges: for badge in badges: - author_type = badge["liveChatAuthorBadgeRenderer"]["accessibility"]["accessibilityData"]["label"] + author_type = badge["liveChatAuthorBadgeRenderer"]["accessibility"]["accessibilityData"]["label"] if author_type == '確認済み': isVerified = True if author_type == '所有者': @@ -72,12 +71,11 @@ class BaseRenderer: if author_type == 'モデレーター': isChatModerator = True return isVerified, isChatOwner, isChatSponsor, isChatModerator - + def get_id(self): return self.renderer.get('id') - - def get_publishedat(self,timestamp): - dt = datetime.datetime.fromtimestamp(int(timestamp)/1000000) + + def get_publishedat(self, timestamp): + dt = datetime.datetime.fromtimestamp(int(timestamp) / 1000000) return dt.astimezone(pytz.utc).isoformat( - timespec='milliseconds').replace('+00:00','Z') - \ No newline at end of file + timespec='milliseconds').replace('+00:00', 'Z') diff --git a/pytchat/processors/compatible/renderer/currency.py b/pytchat/processors/compatible/renderer/currency.py index 0ec60a8..00d683c 100644 --- a/pytchat/processors/compatible/renderer/currency.py +++ b/pytchat/processors/compatible/renderer/currency.py @@ -35,4 +35,4 @@ symbols = { "NOK\xa0": {"fxtext": "NOK", "jptext": "ノルウェー・クローネ"}, "BAM\xa0": {"fxtext": "BAM", "jptext": "ボスニア・兌換マルカ"}, "SGD\xa0": {"fxtext": "SGD", "jptext": "シンガポール・ドル"} -} \ No newline at end of file +} diff --git a/pytchat/processors/compatible/renderer/legacypaid.py b/pytchat/processors/compatible/renderer/legacypaid.py index 1b31631..b406c2c 100644 --- a/pytchat/processors/compatible/renderer/legacypaid.py +++ b/pytchat/processors/compatible/renderer/legacypaid.py @@ -1,4 +1,6 @@ from .base import BaseRenderer + + class LiveChatLegacyPaidMessageRenderer(BaseRenderer): def __init__(self, item): super().__init__(item, "newSponsorEvent") @@ -8,36 +10,33 @@ class LiveChatLegacyPaidMessageRenderer(BaseRenderer): message = self.get_message(self.renderer) return { - "type" : self.chattype, - "liveChatId" : "", - "authorChannelId" : self.renderer.get("authorExternalChannelId"), - "publishedAt" : self.get_publishedat(self.renderer.get("timestampUsec",0)), - "hasDisplayContent" : True, - "displayMessage" : message, - + "type": self.chattype, + "liveChatId": "", + "authorChannelId": self.renderer.get("authorExternalChannelId"), + "publishedAt": self.get_publishedat(self.renderer.get("timestampUsec", 0)), + "hasDisplayContent": True, + "displayMessage": message, + } def get_authordetails(self): authorExternalChannelId = self.renderer.get("authorExternalChannelId") - #parse subscriber type + # parse subscriber type isVerified, isChatOwner, _, isChatModerator = ( self.get_badges(self.renderer) ) - return { - "channelId" : authorExternalChannelId, - "channelUrl" : "http://www.youtube.com/channel/"+authorExternalChannelId, - "displayName" : self.renderer["authorName"]["simpleText"], - "profileImageUrl" : self.renderer["authorPhoto"]["thumbnails"][1]["url"] , - "isVerified" : isVerified, - "isChatOwner" : isChatOwner, - "isChatSponsor" : True, - "isChatModerator" : isChatModerator - } + return { + "channelId": authorExternalChannelId, + "channelUrl": "http://www.youtube.com/channel/" + authorExternalChannelId, + "displayName": self.renderer["authorName"]["simpleText"], + "profileImageUrl": self.renderer["authorPhoto"]["thumbnails"][1]["url"], + "isVerified": isVerified, + "isChatOwner": isChatOwner, + "isChatSponsor": True, + "isChatModerator": isChatModerator + } - - def get_message(self,renderer): + def get_message(self, renderer): message = (renderer["eventText"]["runs"][0]["text"] - )+' / '+(renderer["detailText"]["simpleText"]) + ) + ' / ' + (renderer["detailText"]["simpleText"]) return message - - diff --git a/pytchat/processors/compatible/renderer/membership.py b/pytchat/processors/compatible/renderer/membership.py index 5721549..ced2d06 100644 --- a/pytchat/processors/compatible/renderer/membership.py +++ b/pytchat/processors/compatible/renderer/membership.py @@ -25,7 +25,7 @@ class LiveChatMembershipItemRenderer(BaseRenderer): ) return { "channelId": authorExternalChannelId, - "channelUrl": "http://www.youtube.com/channel/"+authorExternalChannelId, + "channelUrl": "http://www.youtube.com/channel/" + authorExternalChannelId, "displayName": self.renderer["authorName"]["simpleText"], "profileImageUrl": self.renderer["authorPhoto"]["thumbnails"][1]["url"], "isVerified": isVerified, @@ -35,6 +35,6 @@ class LiveChatMembershipItemRenderer(BaseRenderer): } def get_message(self, renderer): - message = ''.join([mes.get("text", "") for mes in renderer["headerSubtext"]["runs"]]) + message = ''.join([mes.get("text", "") + for mes in renderer["headerSubtext"]["runs"]]) return message, [message] - diff --git a/pytchat/processors/compatible/renderer/paidmessage.py b/pytchat/processors/compatible/renderer/paidmessage.py index d5c2615..c47e75a 100644 --- a/pytchat/processors/compatible/renderer/paidmessage.py +++ b/pytchat/processors/compatible/renderer/paidmessage.py @@ -3,6 +3,7 @@ from . import currency from .base import BaseRenderer superchat_regex = re.compile(r"^(\D*)(\d{1,3}(,\d{3})*(\.\d*)*\b)$") + class LiveChatPaidMessageRenderer(BaseRenderer): def __init__(self, item): super().__init__(item, "superChatEvent") @@ -10,32 +11,32 @@ class LiveChatPaidMessageRenderer(BaseRenderer): def get_snippet(self): authorName = self.renderer["authorName"]["simpleText"] message = self.get_message(self.renderer) - amountDisplayString, symbol, amountMicros =( + amountDisplayString, symbol, amountMicros = ( self.get_amountdata(self.renderer) ) return { - "type" : self.chattype, - "liveChatId" : "", - "authorChannelId" : self.renderer.get("authorExternalChannelId"), - "publishedAt" : self.get_publishedat(self.renderer.get("timestampUsec",0)), - "hasDisplayContent" : True, - "displayMessage" : amountDisplayString+" from "+authorName+': \"'+ message+'\"', - "superChatDetails" : { - "amountMicros" : amountMicros, - "currency" : currency.symbols[symbol]["fxtext"] if currency.symbols.get(symbol) else symbol, - "amountDisplayString" : amountDisplayString, - "tier" : 0, - "backgroundColor" : self.renderer.get("bodyBackgroundColor", 0) + "type": self.chattype, + "liveChatId": "", + "authorChannelId": self.renderer.get("authorExternalChannelId"), + "publishedAt": self.get_publishedat(self.renderer.get("timestampUsec", 0)), + "hasDisplayContent": True, + "displayMessage": amountDisplayString + " from " + authorName + ': \"' + message + '\"', + "superChatDetails": { + "amountMicros": amountMicros, + "currency": currency.symbols[symbol]["fxtext"] if currency.symbols.get(symbol) else symbol, + "amountDisplayString": amountDisplayString, + "tier": 0, + "backgroundColor": self.renderer.get("bodyBackgroundColor", 0) } } - def get_amountdata(self,renderer): + def get_amountdata(self, renderer): amountDisplayString = renderer["purchaseAmountText"]["simpleText"] m = superchat_regex.search(amountDisplayString) if m: symbol = m.group(1) - amountMicros = int(float(m.group(2).replace(',',''))*1000000) + amountMicros = int(float(m.group(2).replace(',', '')) * 1000000) else: symbol = "" amountMicros = 0 - return amountDisplayString, symbol, amountMicros \ No newline at end of file + return amountDisplayString, symbol, amountMicros diff --git a/pytchat/processors/compatible/renderer/paidsticker.py b/pytchat/processors/compatible/renderer/paidsticker.py index 20abf32..e7cc87d 100644 --- a/pytchat/processors/compatible/renderer/paidsticker.py +++ b/pytchat/processors/compatible/renderer/paidsticker.py @@ -3,46 +3,45 @@ from . import currency from .base import BaseRenderer superchat_regex = re.compile(r"^(\D*)(\d{1,3}(,\d{3})*(\.\d*)*\b)$") + class LiveChatPaidStickerRenderer(BaseRenderer): def __init__(self, item): super().__init__(item, "superStickerEvent") def get_snippet(self): authorName = self.renderer["authorName"]["simpleText"] - amountDisplayString, symbol, amountMicros =( + amountDisplayString, symbol, amountMicros = ( self.get_amountdata(self.renderer) ) return { - "type" : self.chattype, - "liveChatId" : "", - "authorChannelId" : self.renderer.get("authorExternalChannelId"), - "publishedAt" : self.get_publishedat(self.renderer.get("timestampUsec",0)), - "hasDisplayContent" : True, - "displayMessage" : "Super Sticker " + amountDisplayString + " from "+authorName, - "superStickerDetails" : { - "superStickerMetaData" : { + "type": self.chattype, + "liveChatId": "", + "authorChannelId": self.renderer.get("authorExternalChannelId"), + "publishedAt": self.get_publishedat(self.renderer.get("timestampUsec", 0)), + "hasDisplayContent": True, + "displayMessage": "Super Sticker " + amountDisplayString + " from " + authorName, + "superStickerDetails": { + "superStickerMetaData": { "stickerId": "", "altText": "", - "language": "" + "language": "" }, - "amountMicros" : amountMicros, - "currency" : currency.symbols[symbol]["fxtext"] if currency.symbols.get(symbol) else symbol, - "amountDisplayString" : amountDisplayString, - "tier" : 0, - "backgroundColor" : self.renderer.get("bodyBackgroundColor", 0) + "amountMicros": amountMicros, + "currency": currency.symbols[symbol]["fxtext"] if currency.symbols.get(symbol) else symbol, + "amountDisplayString": amountDisplayString, + "tier": 0, + "backgroundColor": self.renderer.get("bodyBackgroundColor", 0) } } - def get_amountdata(self,renderer): + def get_amountdata(self, renderer): amountDisplayString = renderer["purchaseAmountText"]["simpleText"] m = superchat_regex.search(amountDisplayString) if m: symbol = m.group(1) - amountMicros = int(float(m.group(2).replace(',',''))*1000000) + amountMicros = int(float(m.group(2).replace(',', '')) * 1000000) else: symbol = "" amountMicros = 0 return amountDisplayString, symbol, amountMicros - - diff --git a/pytchat/processors/compatible/renderer/textmessage.py b/pytchat/processors/compatible/renderer/textmessage.py index dae62f1..c40aca2 100644 --- a/pytchat/processors/compatible/renderer/textmessage.py +++ b/pytchat/processors/compatible/renderer/textmessage.py @@ -1,4 +1,6 @@ from .base import BaseRenderer + + class LiveChatTextMessageRenderer(BaseRenderer): def __init__(self, item): super().__init__(item, "textMessageEvent") diff --git a/pytchat/processors/default/processor.py b/pytchat/processors/default/processor.py index 3ba14c0..c4f8f47 100644 --- a/pytchat/processors/default/processor.py +++ b/pytchat/processors/default/processor.py @@ -20,13 +20,13 @@ class Chatdata: if self.interval == 0: time.sleep(1) return - time.sleep(self.interval/len(self.items)) + time.sleep(self.interval / len(self.items)) async def tick_async(self): if self.interval == 0: await asyncio.sleep(1) return - await asyncio.sleep(self.interval/len(self.items)) + await asyncio.sleep(self.interval / len(self.items)) class DefaultProcessor(ChatProcessor): @@ -62,7 +62,7 @@ class DefaultProcessor(ChatProcessor): return None try: renderer = self._get_renderer(item) - if renderer == None: + if renderer is None: return None renderer.get_snippet() diff --git a/pytchat/processors/default/renderer/base.py b/pytchat/processors/default/renderer/base.py index 4a1aa41..1e42619 100644 --- a/pytchat/processors/default/renderer/base.py +++ b/pytchat/processors/default/renderer/base.py @@ -1,6 +1,10 @@ from datetime import datetime + + class Author: pass + + class BaseRenderer: def __init__(self, item, chattype): self.renderer = list(item.values())[0] @@ -10,65 +14,62 @@ class BaseRenderer: def get_snippet(self): self.type = self.chattype self.id = self.renderer.get('id') - timestampUsec = int(self.renderer.get("timestampUsec",0)) - self.timestamp = int(timestampUsec/1000) + timestampUsec = int(self.renderer.get("timestampUsec", 0)) + self.timestamp = int(timestampUsec / 1000) tst = self.renderer.get("timestampText") if tst: self.elapsedTime = tst.get("simpleText") else: self.elapsedTime = "" self.datetime = self.get_datetime(timestampUsec) - self.message ,self.messageEx = self.get_message(self.renderer) - self.id = self.renderer.get('id') - self.amountValue= 0.0 + self.message, self.messageEx = self.get_message(self.renderer) + self.id = self.renderer.get('id') + self.amountValue = 0.0 self.amountString = "" - self.currency= "" + self.currency = "" self.bgColor = 0 def get_authordetails(self): self.author.badgeUrl = "" - (self.author.isVerified, - self.author.isChatOwner, - self.author.isChatSponsor, - self.author.isChatModerator) = ( + (self.author.isVerified, + self.author.isChatOwner, + self.author.isChatSponsor, + self.author.isChatModerator) = ( self.get_badges(self.renderer) ) self.author.channelId = self.renderer.get("authorExternalChannelId") - self.author.channelUrl = "http://www.youtube.com/channel/"+self.author.channelId - self.author.name = self.renderer["authorName"]["simpleText"] - self.author.imageUrl= self.renderer["authorPhoto"]["thumbnails"][1]["url"] - + self.author.channelUrl = "http://www.youtube.com/channel/" + self.author.channelId + self.author.name = self.renderer["authorName"]["simpleText"] + self.author.imageUrl = self.renderer["authorPhoto"]["thumbnails"][1]["url"] - - def get_message(self,renderer): + def get_message(self, renderer): message = '' message_ex = [] if renderer.get("message"): - runs=renderer["message"].get("runs") + runs = renderer["message"].get("runs") if runs: for r in runs: if r: if r.get('emoji'): - message += r['emoji'].get('shortcuts',[''])[0] - message_ex.append(r['emoji']['image']['thumbnails'][1].get('url')) + message += r['emoji'].get('shortcuts', [''])[0] + message_ex.append( + r['emoji']['image']['thumbnails'][1].get('url')) else: - message += r.get('text','') - message_ex.append(r.get('text','')) + message += r.get('text', '') + message_ex.append(r.get('text', '')) return message, message_ex - - - def get_badges(self,renderer): + def get_badges(self, renderer): self.author.type = '' isVerified = False isChatOwner = False isChatSponsor = False isChatModerator = False - badges=renderer.get("authorBadges") + badges = renderer.get("authorBadges") if badges: for badge in badges: if badge["liveChatAuthorBadgeRenderer"].get("icon"): - author_type = badge["liveChatAuthorBadgeRenderer"]["icon"]["iconType"] + author_type = badge["liveChatAuthorBadgeRenderer"]["icon"]["iconType"] self.author.type = author_type if author_type == 'VERIFIED': isVerified = True @@ -81,13 +82,10 @@ class BaseRenderer: self.author.type = 'MEMBER' self.get_badgeurl(badge) return isVerified, isChatOwner, isChatSponsor, isChatModerator - - def get_badgeurl(self,badge): + def get_badgeurl(self, badge): self.author.badgeUrl = badge["liveChatAuthorBadgeRenderer"]["customThumbnail"]["thumbnails"][0]["url"] - - - def get_datetime(self,timestamp): - dt = datetime.fromtimestamp(timestamp/1000000) - return dt.strftime('%Y-%m-%d %H:%M:%S') \ No newline at end of file + def get_datetime(self, timestamp): + dt = datetime.fromtimestamp(timestamp / 1000000) + return dt.strftime('%Y-%m-%d %H:%M:%S') diff --git a/pytchat/processors/default/renderer/currency.py b/pytchat/processors/default/renderer/currency.py index 37f353e..4d4c314 100644 --- a/pytchat/processors/default/renderer/currency.py +++ b/pytchat/processors/default/renderer/currency.py @@ -35,4 +35,4 @@ symbols = { "NOK\xa0": {"fxtext": "NOK", "jptext": "ノルウェー・クローネ"}, "BAM\xa0": {"fxtext": "BAM", "jptext": "ボスニア・兌換マルカ"}, "SGD\xa0": {"fxtext": "SGD", "jptext": "シンガポール・ドル"} -} \ No newline at end of file +} diff --git a/pytchat/processors/default/renderer/legacypaid.py b/pytchat/processors/default/renderer/legacypaid.py index 12dfde5..ee238cf 100644 --- a/pytchat/processors/default/renderer/legacypaid.py +++ b/pytchat/processors/default/renderer/legacypaid.py @@ -1,18 +1,15 @@ from .base import BaseRenderer + + class LiveChatLegacyPaidMessageRenderer(BaseRenderer): def __init__(self, item): super().__init__(item, "newSponsor") - - def get_authordetails(self): super().get_authordetails() - self.author.isChatSponsor = True + self.author.isChatSponsor = True - - def get_message(self,renderer): + def get_message(self, renderer): message = (renderer["eventText"]["runs"][0]["text"] - )+' / '+(renderer["detailText"]["simpleText"]) + ) + ' / ' + (renderer["detailText"]["simpleText"]) return message - - diff --git a/pytchat/processors/default/renderer/membership.py b/pytchat/processors/default/renderer/membership.py index 726b617..7a7d100 100644 --- a/pytchat/processors/default/renderer/membership.py +++ b/pytchat/processors/default/renderer/membership.py @@ -10,6 +10,6 @@ class LiveChatMembershipItemRenderer(BaseRenderer): self.author.isChatSponsor = True def get_message(self, renderer): - message = ''.join([mes.get("text", "") for mes in renderer["headerSubtext"]["runs"]]) + message = ''.join([mes.get("text", "") + for mes in renderer["headerSubtext"]["runs"]]) return message, [message] - diff --git a/pytchat/processors/default/renderer/paidmessage.py b/pytchat/processors/default/renderer/paidmessage.py index c215552..9e69ab4 100644 --- a/pytchat/processors/default/renderer/paidmessage.py +++ b/pytchat/processors/default/renderer/paidmessage.py @@ -3,30 +3,29 @@ from . import currency from .base import BaseRenderer superchat_regex = re.compile(r"^(\D*)(\d{1,3}(,\d{3})*(\.\d*)*\b)$") + class LiveChatPaidMessageRenderer(BaseRenderer): def __init__(self, item): super().__init__(item, "superChat") - def get_snippet(self): super().get_snippet() - amountDisplayString, symbol, amount =( + amountDisplayString, symbol, amount = ( self.get_amountdata(self.renderer) ) - self.amountValue= amount + self.amountValue = amount self.amountString = amountDisplayString - self.currency= currency.symbols[symbol]["fxtext"] if currency.symbols.get(symbol) else symbol - self.bgColor= self.renderer.get("bodyBackgroundColor", 0) - + self.currency = currency.symbols[symbol]["fxtext"] if currency.symbols.get( + symbol) else symbol + self.bgColor = self.renderer.get("bodyBackgroundColor", 0) - - def get_amountdata(self,renderer): + def get_amountdata(self, renderer): amountDisplayString = renderer["purchaseAmountText"]["simpleText"] m = superchat_regex.search(amountDisplayString) if m: symbol = m.group(1) - amount = float(m.group(2).replace(',','')) + amount = float(m.group(2).replace(',', '')) else: symbol = "" amount = 0.0 - return amountDisplayString, symbol, amount \ No newline at end of file + return amountDisplayString, symbol, amount diff --git a/pytchat/processors/default/renderer/paidsticker.py b/pytchat/processors/default/renderer/paidsticker.py index 8ec4828..b474e71 100644 --- a/pytchat/processors/default/renderer/paidsticker.py +++ b/pytchat/processors/default/renderer/paidsticker.py @@ -3,37 +3,31 @@ from . import currency from .base import BaseRenderer superchat_regex = re.compile(r"^(\D*)(\d{1,3}(,\d{3})*(\.\d*)*\b)$") + class LiveChatPaidStickerRenderer(BaseRenderer): def __init__(self, item): super().__init__(item, "superSticker") - def get_snippet(self): super().get_snippet() - amountDisplayString, symbol, amount =( + amountDisplayString, symbol, amount = ( self.get_amountdata(self.renderer) ) self.amountValue = amount self.amountString = amountDisplayString - self.currency = currency.symbols[symbol]["fxtext"] if currency.symbols.get(symbol) else symbol + self.currency = currency.symbols[symbol]["fxtext"] if currency.symbols.get( + symbol) else symbol self.bgColor = self.renderer.get("moneyChipBackgroundColor", 0) - self.sticker = "https:"+self.renderer["sticker"]["thumbnails"][0]["url"] - + self.sticker = "https:" + \ + self.renderer["sticker"]["thumbnails"][0]["url"] - - def get_amountdata(self,renderer): + def get_amountdata(self, renderer): amountDisplayString = renderer["purchaseAmountText"]["simpleText"] m = superchat_regex.search(amountDisplayString) if m: symbol = m.group(1) - amount = float(m.group(2).replace(',','')) + amount = float(m.group(2).replace(',', '')) else: symbol = "" amount = 0.0 return amountDisplayString, symbol, amount - - - - - - diff --git a/pytchat/processors/default/renderer/textmessage.py b/pytchat/processors/default/renderer/textmessage.py index 131f8b3..475a70d 100644 --- a/pytchat/processors/default/renderer/textmessage.py +++ b/pytchat/processors/default/renderer/textmessage.py @@ -1,4 +1,6 @@ from .base import BaseRenderer + + class LiveChatTextMessageRenderer(BaseRenderer): def __init__(self, item): super().__init__(item, "textMessage") diff --git a/pytchat/processors/dummy_processor.py b/pytchat/processors/dummy_processor.py index e2e406d..da02573 100644 --- a/pytchat/processors/dummy_processor.py +++ b/pytchat/processors/dummy_processor.py @@ -1,8 +1,10 @@ from .chat_processor import ChatProcessor + class DummyProcessor(ChatProcessor): ''' Dummy processor just returns received chat_components directly. ''' + def process(self, chat_components: list): return chat_components diff --git a/pytchat/processors/html_archiver.py b/pytchat/processors/html_archiver.py index 9249cf4..397d31e 100644 --- a/pytchat/processors/html_archiver.py +++ b/pytchat/processors/html_archiver.py @@ -1,18 +1,18 @@ -import csv import os import re from .chat_processor import ChatProcessor from .default.processor import DefaultProcessor -PATTERN = re.compile(r"(.*)\(([0-9]+)\)$") -fmt_headers = ['datetime','elapsed','authorName','message','superchat' - ,'type','authorChannel'] +PATTERN = re.compile(r"(.*)\(([0-9]+)\)$") +fmt_headers = ['datetime', 'elapsed', 'authorName', + 'message', 'superchat', 'type', 'authorChannel'] HEADER_HTML = ''' ''' + class HTMLArchiver(ChatProcessor): ''' HtmlArchiver saves chat data as HTML table format. @@ -21,7 +21,7 @@ class HTMLArchiver(ChatProcessor): def __init__(self, save_path): super().__init__() self.save_path = self._checkpath(save_path) - with open(self.save_path, mode='a', encoding = 'utf-8') as f: + with open(self.save_path, mode='a', encoding='utf-8') as f: f.write(HEADER_HTML) f.write('