Last active
April 30, 2021 13:53
-
-
Save catbaron0/2b1e824df1e285d7bc9ff882bc22132c to your computer and use it in GitHub Desktop.
Notify the comments from lizhi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
import requests | |
import re | |
import time | |
import subprocess | |
import emoji | |
import time | |
from datetime import datetime | |
import logging | |
now = datetime.now().strftime("%Y%m%d%H%M%S") | |
logger = logging.getLogger(__name__) | |
logging.basicConfig( | |
filename=f"log.{now}", | |
level=logging.INFO, | |
format='%(levelname)s:%(asctime)s %(message)s' | |
) | |
def deEmojify(text): | |
return ''.join([c for c in text if c not in emoji.UNICODE_EMOJI['en']]) | |
parser = argparse.ArgumentParser() | |
parser.add_argument( | |
'-u', '--url', dest='url', type=str, required=True, | |
help='The url shared from lizhi' | |
) | |
parser.add_argument( | |
'-c', '--count-only', dest='count_only', action='store_true', | |
help='Only inform the count of messages.' | |
) | |
args = parser.parse_args() | |
live_url = args.url | |
r = requests.get(live_url, allow_redirects=False) | |
if r.status_code == 302: | |
live_url = r.headers['Location'] | |
liveid = re.search(r'liveId=(\d+)', live_url).group(1) | |
msg_time = int(time.time() * 1000) | |
while True: | |
time.sleep(1) | |
url=f"https://appweb.lizhi.fm/live/comments?liveId={liveid}&start={msg_time}&count=50" | |
res = requests.get(url) | |
try: | |
json_res = res.json() | |
except Exception as e: | |
print(f"Failed to read comments: {e}") | |
print(res.text) | |
continue | |
msg_time = json_res['comments']['end'] | |
msg_count = len(json_res['comments']['list']) | |
if args.count_only and msg_count > 0: | |
speak_msg = f"你收到了 {msg_count} 条消息." | |
cmd = ["say", "-v", "Ting-Ting", speak_msg] | |
subprocess.call(cmd) | |
else: | |
for msg in json_res['comments']['list']: | |
user_name = deEmojify(msg['userName']) | |
if not user_name.strip(): | |
user_name = f"{user_name} 个空白" | |
comment = msg['comment'].replace(' ', ',') | |
speak_msg = f"{user_name} 说: {comment}" | |
logger.info(speak_msg) | |
cmd = ["say", "-v", "Ting-Ting", speak_msg] | |
subprocess.call(cmd) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment