Welcome folks today in this blog post we will be using the youtube live streaming
api to get all the live stream messages and comments in command line using the youtube video url. All the full source code of the application is shown below.
Get Started
In order to get started you need to install the below library using the pip
command as shown below
pip install pytchat
After this you need to make an app.py
file and copy paste the following code
app.py
1 2 3 4 5 6 7 |
import pytchat chat = pytchat.create(video_id="aIqyZyfjk1w") while chat.is_alive(): for c in chat.get().sync_items(): print(f"{c.datetime} [{c.author.name}] - {c.message}") |
As you can see we are importing the pytchat
module at the very top and then we are using the create()
method and passing the video_id
as the first argument. And then we are using the while
loop to get all the chat
messages of the live stream and then we are printing all the messages
with date and time and also the author name and the actual message as shown below
Now we will be modifying the code such that if we enter the url
of the live stream then also the program runs by extracting the video_id
from the youtube video url as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import pytchat def getVideoId(url): from urllib.parse import urlparse,parse_qs if url.startswith(('youtu','www')): url = 'http://' + url query = urlparse(url) if 'youtube' in query.hostname: if query.path == "/watch": return parse_qs(query.query)['v'][0] elif query.path.startswith(('/embed/','/v/')): return query.path.split('/')[2] elif 'youtu.be' in query.hostname: return query.path[1:] else: raise ValueError url = input("Enter the Youtube Video URL") chat = pytchat.create(video_id=getVideoId(url)) while chat.is_alive(): for c in chat.get().sync_items(): print(f"{c.datetime} [{c.author.name}] - {c.message}") |
As you can see we are now asking the user
to input the url
of the youtube live stream video that you want to extract
messages and comments. Then we are defining a new function
to extract the videoid
from the url. Inside this we are using the urllib
package to extract the video id from the url and then the messages are displaying as you can see below