In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article is to share with you the content of how Python implements bilibili's UP master and assistant. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Preface
Get the effect first
It's like this when there's a barrage.
Why are the monitors of the two screenshots different? Ah, speaking of tears, I wrote this code live until 2: 00 in the morning that night. After I finished the code, I was going to stuff the raspberry pie and the display screen into a cardboard box. I don't know where the damage was, and the screen didn't light up.
But fortunately, there is no problem with raspberry pie. I don't have much gossip. Let's take a look at my thoughts on frame selection.
Frame selection
Why did you end up choosing Python, a language I don't know? Because I wanted the program to run on raspberry pie in the end, I first investigated several ways to build a GUI interface on raspberry pie.
PyQt (python)
Pygame (python)
Electron (javascript)
Flutter (dart)
Although I am more familiar with 3 and 4, after all, the performance of raspberry pie is limited, so I have to abandon it. I'm not familiar with it, but in my plan, I don't need some standardized UI components. So I finally chose the framework of pygame, and the pygame environment is also installed by default in the raspberry pie system. Although I have never written python, I have always wanted to learn the name of python. I just want to practice with this project.
Function point
Show date and time
Displays the raspberry pie's current LAN IP
Displays the current number of UP main fans
Show unread messages from bilibili
Displays the total number of bilibili videos played
Displays the total number of video likes
Displays the total number of charges obtained
Display the popularity of the live broadcast room
Show live room on-screen comment
Read out the live room on-screen comment (TTS)
Is the function quite rich? it took less than two days to write the first line of code to complete, which also proves the high efficiency of using python development. Let's talk about what problems I encountered in the development of these functions and how I solved them.
Pygame framework
Pygame official website: https://www.pygame.org/
Pygame is the most popular game development framework in the python environment, and it's easier to use the game framework to develop when I don't need the common UI components.
# install pygamepip install pygame
Example of using frame Foundation
# introduce pygame and sysimport pygame,sys # to define a run_game function, put all the initialization logic in def run_game (): # initialize the pygame engine pygame.init () # set the pygame window size, and automatically identify the resolution if it is set to 0 score 0, which is equivalent to window maximization screen = pygame.display.set_mode ((600400)) # infinite loop The game's main loop while True: # listen message for event in pygame.event.get (): # when listening for pygame exit, trigger sys.exit exit application if event.type = = pygame.QUIT: sys.exit () # clear screen screen.fill (BG_COLOR) # the main logic drawn by the game is placed here # refresh screen pygame.display.update () # execute run_game function run_game ()
Python may be friendly to new programmers and will not have too many preconceived notions of code writing. But for me, who already has experience in developing other languages, it took me a while to get used to its syntax.
Pygame loads fonts to display text
# 220 is the font size my_font = pygame.font.Font (". / path / font .ttf", 220) # my_font.render (text content, anti-aliasing, text color Text background color) text_element = my_font.render ("text content", 1, (255255255)) # calculates the width and height of the rendered text text_width, text_height = my_font.size ("text content") # draws the text element to the specified coordinates on the screen (the upper left corner of the element is the origin) screen.blit (text_element, (100100) python gets the date and time
Import time def getTime (): # get system local time localtime = time.localtime () # format local time as year, month, day, date_str = time.strftime ("% Y% m,% d", localtime) # format local time as 24-hour hm_str = time.strftime ("% HGV% M", localtime) # format local time to get seconds second_str = time.strftime ("% S", localtime)
Call getTime in the main loop of pygame and draw the time text to the screen, and a small clock is done.
Displays the raspberry pie's current LAN IP
Why display the current IP, because most of the time I don't connect the mouse and keyboard to the raspberry pie, so after displaying IP, you can connect the raspberry pie directly through VNC or SSH.
There is a scheme for Python to obtain local area network IP on the Internet. This is the best solution I've ever used: P
Import socket def get_host_ip (): try: s = socket.socket (socket.AF_INET, socket.SOCK_DGRAM) s.connect (('8.8.8.8mm, 80)) ip = s.getsockname () [0] finally: s.close () return ip displays all kinds of data of bilibili
The most important thing here is to grab all kinds of API interfaces of bilibili. There is also a wild API document sorted out by enthusiastic netizens, so you can check and use what you need.
Https://github.com/SocialSisterYi/bilibili-API-collect
Some of bilibili's API requires authentication, so we need to extract it from the chrome browser ourselves. We will mainly use two cookie fields.
SESSDATA
CSRF Token (bili_jct)
Import requests # request live room on-screen comment list res = requests.get ('https://api.live.bilibili.com/xlive/web-room/v1/dM/gethistory?roomid='+BILI_LIVEID) data = res.json ())
But requests executes synchronously, blocking the execution of the main thread. For example, in this case, if I directly use requests to initiate a request, the main logical loop of the pygame is stuck when the request is made, which is certainly not what I want. There are many tutorials to change asynchronism on the Internet, so I won't repeat them. Here, I use another library that supports asynchronism, called httpx, which is very similar to ordinary requests.
Import httpx async with httpx.AsyncClient () as client: res = await client.get ('https://api.live.bilibili.com/xlive/web-room/v1/dM/gethistory?roomid='+BILI_LIVEID) data = res.json ()
However, in my design, I have to request five bilibili interfaces to get all the data fields displayed. Obviously, this can be optimized, but I finally chose to use uniCloud to develop a cloud function, and then URL this cloud function to python for use. As I mentioned in the video tutorial, we can use uniCloud to develop the back-end interface, and then the front end uses Flutter or any other framework, which does not need to be limited to uniapp.
Read the live room on-screen comment (TTS) import pyttsx3 pyttsx3.speak ("Hello")
Yes, it is easy to use this pyttsx3 to do TTS, but it is done using the services that come with the system.
Windows system: SAPI5
MacOS:NSSpeechSynthesizer
Linux:eSpeak
The advantage is like the previous code, which is very easy to use. The disadvantage is that it is not unified in each platform, and cross-end will encounter some compatibility problems. For example, when I develop on mac and run on linux, the effect is different. This method is also synchronized by default, that is, the main thread is blocked when the voice is played, and the main thread will not continue to execute until the voice playback is over. This experience is too bad. I have to wait until the barrage is over before I can run on the screen.
Solution: use Thread to open child threads for execution
From threading import Thread Thread (target=pyttsx3.speak,args=). Start () Thank you for your reading! This is the end of this article on "how to achieve bilibili's UP Master Assistant in Python". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.