a python library for fetching youtube live chat.
Project description
pytchat
pytchat is a python library for fetching youtube live chat.
Description
pytchat is a python library for fetching youtube live chat without using youtube api, Selenium or BeautifulSoup.
pytchatは、YouTubeチャットを閲覧するためのpythonライブラリです。
Other features:
- Customizable chat data processors including youtube api compatible one.
- Available on asyncio context.
- Quick fetching of initial chat data by generating continuation params instead of web scraping.
For more detailed information, see wiki.
より詳細な解説はwikiを参照してください。
Install
pip install pytchat
Examples
CLI
One-liner command. Save chat data to html, with embedded custom emojis.
$ pytchat -v https://www.youtube.com/watch?v=ZJ6Q4U_Vg6s -o "c:/temp/"
# options:
# -v : Video ID or URL that includes ID
# -o : output directory (default path: './')
# saved filename is [video_id].html
on-demand mode
from pytchat import LiveChat
livechat = LiveChat(video_id = "Zvp1pJpie4I")
# It is also possible to specify a URL that includes the video ID:
# livechat = LiveChat("https://www.youtube.com/watch?v=Zvp1pJpie4I")
while livechat.is_alive():
try:
chatdata = livechat.get()
for c in chatdata.items:
print(f"{c.datetime} [{c.author.name}]- {c.message}")
chatdata.tick()
except KeyboardInterrupt:
livechat.terminate()
break
callback mode
from pytchat import LiveChat
import time
def main():
livechat = LiveChat(video_id = "Zvp1pJpie4I", callback = disp)
while livechat.is_alive():
#other background operation.
time.sleep(1)
livechat.terminate()
#callback function (automatically called)
def disp(chatdata):
for c in chatdata.items:
print(f"{c.datetime} [{c.author.name}]- {c.message}")
chatdata.tick()
if __name__ == '__main__':
main()
asyncio context:
from pytchat import LiveChatAsync
from concurrent.futures import CancelledError
import asyncio
async def main():
livechat = LiveChatAsync("Zvp1pJpie4I", callback = func)
while livechat.is_alive():
#other background operation.
await asyncio.sleep(3)
#callback function is automatically called.
async def func(chatdata):
for c in chatdata.items:
print(f"{c.datetime} [{c.author.name}]-{c.message} {c.amountString}")
await chatdata.tick_async()
if __name__ == '__main__':
try:
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
except CancelledError:
pass
youtube api compatible processor:
from pytchat import LiveChat, CompatibleProcessor
import time
chat = LiveChat("Zvp1pJpie4I",
processor = CompatibleProcessor() )
while chat.is_alive():
try:
data = chat.get()
polling = data['pollingIntervalMillis']/1000
for c in data['items']:
if c.get('snippet'):
print(f"[{c['authorDetails']['displayName']}]"
f"-{c['snippet']['displayMessage']}")
time.sleep(polling/len(data['items']))
except KeyboardInterrupt:
chat.terminate()
replay:
If specified video is not live, automatically try to fetch archived chat data.
from pytchat import LiveChat
def main():
#seektime (seconds): start position of chat.
chat = LiveChat("ojes5ULOqhc", seektime = 60*30)
print('Replay from 30:00')
try:
while chat.is_alive():
data = chat.get()
for c in data.items:
print(f"{c.elapsedTime} [{c.author.name}]-{c.message} {c.amountString}")
data.tick()
except KeyboardInterrupt:
chat.terminate()
if __name__ == '__main__':
main()
Extract archived chat data as HTML or tab separated values.
from pytchat import HTMLArchiver, Extractor
video_id = "*******"
ex = Extractor(
video_id,
div=10,
processor=HTMLArchiver("c:/test.html")
)
ex.extract()
print("finished.")
Structure of Default Processor
Each item can be got with items function.
| name | type | remarks |
|---|---|---|
| type | str | "superChat","textMessage","superSticker","newSponsor" |
| id | str | |
| message | str | emojis are represented by ":(shortcut text):" |
| messageEx | str | list of message texts and emoji dicts(id, txt, url). |
| timestamp | int | unixtime milliseconds |
| datetime | str | e.g. "2019-10-10 12:34:56" |
| elapsedTime | str | elapsed time. (e.g. "1:02:27") *Replay Only. |
| amountValue | float | e.g. 1,234.0 |
| amountString | str | e.g. "$ 1,234" |
| currency | str | ISO 4217 currency codes (e.g. "USD") |
| bgColor | int | RGB Int |
| author | object | see below |
Structure of author object.
| name | type | remarks |
|---|---|---|
| name | str | |
| channelId | str | *chatter's channel ID. |
| channelUrl | str | |
| imageUrl | str | |
| badgeUrl | str | |
| isVerified | bool | |
| isChatOwner | bool | |
| isChatSponsor | bool | |
| isChatModerator | bool |
Licence
Contributes
Great thanks:
Most of source code of CLI refer to:
PetterKraabol / Twitch-Chat-Downloader
Author
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distributions
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file pytchat-0.2.9-py3-none-any.whl.
File metadata
- Download URL: pytchat-0.2.9-py3-none-any.whl
- Upload date:
- Size: 64.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.24.0 setuptools/40.8.0 requests-toolbelt/0.9.1 tqdm/4.41.1 CPython/3.8.6
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9331758a6ce5b3efef600b3ac75a28110fa72a0c5efc4b1badb6931ea1ca9dda
|
|
| MD5 |
2f9653b447208a49db3fd945c8eaa833
|
|
| BLAKE2b-256 |
1de731a977f9c52d2d8b3fb5905e06cb2435f6079fc5ac440147e7075778c068
|