Skip to content

Commit

Permalink
Merge pull request #117 from gakkiyomi/develop
Browse files Browse the repository at this point in the history
v2.0.5 released
  • Loading branch information
gakkiyomi authored Dec 18, 2023
2 parents b34e3e6 + 618fc2f commit 4606b00
Show file tree
Hide file tree
Showing 7 changed files with 125 additions and 8 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ python core.py
- 🧠 自言自语
- 自定义语句池
- 定时发送
- 📑 查看帖子
- 发送评论
- 命令模式
- 命令/聊天模式切换
- (聊天模式也可以执行命令)
Expand Down
4 changes: 3 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,6 @@ click==8.1.3
objprint==0.2.3
colorama==0.4.6
termcolor==2.4.0
prettytable==3.9.0
prettytable==3.9.0
bs4==0.0.1
html2text==2020.1.16
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@

# What packages are required for this module to be executed?
REQUIRED = [
'requests', 'websocket-client', 'click', 'schedule', 'objprint', 'colorama', 'termcolor', 'prettytable'
'requests', 'websocket-client', 'click', 'schedule', 'objprint', 'colorama', 'termcolor', 'prettytable', 'bs4', 'html2text'
]

# What packages are optional?
Expand Down
63 changes: 58 additions & 5 deletions src/api/article.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import json
from enum import Enum
from typing import Any
from typing import Any, Union

import requests

Expand All @@ -11,6 +11,8 @@

from .config import GLOBAL_CONFIG

from bs4 import BeautifulSoup
import html2text

class ArticleType(Enum):
RECENT = 'recent'
Expand All @@ -36,8 +38,25 @@ def thanks(self, api) -> None:
def comment(self, api, comment: str) -> None:
api.comment_article(self.oId, comment)

def get_content(self) -> None:
print("\n"+self.articleOriginalContent)

def get_author(self) -> str:
author_name = self.articleAuthor.get("userNickname", "")
return author_name if author_name != '' else self.articleAuthor["userName"]

def get_tittle(self) -> str:
return self.articleTitle

def get_articleComments(self) -> list[dict[str, Any]]:
return self.articleComments


class ArticleAPI(Base):
def __init__(self):
super().__init__()
self.articles: List[dict] = []

def vote_for_article(self, article_id: str) -> None:
if self.api_key == '':
return None
Expand Down Expand Up @@ -70,12 +89,13 @@ def thanks_for_article(self, article_id: str) -> None:

def list_articles(self, type: ArticleType = ArticleType.RECENT, page: int = 1, size: int = 20) -> dict:
res = requests.get(
f'{GLOBAL_CONFIG.host}/api/articles/{type}?p={page}&size={size}', headers={'User-Agent': UA}, json={
f'{GLOBAL_CONFIG.host}/api/articles/{type.value}?p={page}&size={size}', headers={'User-Agent': UA}, json={
'apiKey': self.api_key
})
response = json.loads(res.text)
if 'code' in response and response['code'] == 0:
return response
self.articles = response["data"]["articles"]
return response["data"]["articles"]
else:
print('获取帖子列表失败: ' + response['msg'])

Expand All @@ -86,12 +106,25 @@ def get_article(self, article_id: str) -> Article:
})
response = json.loads(res.text)
if 'code' in response and response['code'] == 0:
return Article(response['data'])
# print(Article(response['data']))
return Article(response['data']['article'])
else:
print('获取帖子详情失败: ' + response['msg'])

def format_article_list(self, article_list: list[dict[str, Any]]) -> None:
grey_highlight = '\033[1;30;1m'
green_bold = '\033[1;32;1m'
reset_color = '\033[0m'

for index, article in enumerate(article_list):
author_name = article["articleAuthor"].get("userNickname", "") or article["articleAuthor"]["userName"]
colored_name = f'{grey_highlight}{author_name}{reset_color}'
colored_comments = f'{green_bold}{article["articleCommentCount"]}{reset_color}'
formatted_article = f'{str(index + 1).zfill(2)}.[{colored_name}] {article["articleTitle"]} {colored_comments}'
print(formatted_article)

def comment_article(self, article_id: str, comment: str) -> Article:
res = requests.post(f'{GLOBAL_CONFIG.host}/comment/{article_id}', headers={'User-Agent': UA}, json={
res = requests.post(f'{GLOBAL_CONFIG.host}/comment', headers={'User-Agent': UA}, json={
'apiKey': self.api_key,
'articleId': article_id,
'commentAnonymous': False,
Expand All @@ -103,3 +136,23 @@ def comment_article(self, article_id: str, comment: str) -> Article:
print('评论成功')
else:
print('评论失败: ' + response['msg'])

def format_comments_list(self, comments_list: list[dict[str, Any]]) -> None:
green_bold = '\033[1;32;1m'
reset_color = '\033[0m'
yellow = '\x1B[33m'

print(f"{yellow}[{'*' * 60} (评论区) {'*' * 60}]{reset_color}\n")
for index, commenter in enumerate(comments_list):
comment_name = commenter["commenter"].get("userNickname", "") or commenter["commenter"]["userName"]
soup = BeautifulSoup(commenter["commentContent"], 'html.parser')
text_maker = html2text.HTML2Text()
text = text_maker.handle(str(soup))
print(f"{str(index + 1).zfill(2)}.{green_bold}[{comment_name}({commenter['commenter']['userName']})]{reset_color}:{text}")
print(f'{yellow}{"*" * 120}{reset_color}')

def articles_oid(self, index: int = None) -> Union[list[str], str]:
if index is None:
return [oid["oId"] for oid in self.articles]
else:
return self.articles[index - 1]["oId"]
59 changes: 59 additions & 0 deletions src/core/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from objprint import op

from src.api import FishPi, UserInfo
from src.api.article import Article
from src.api.config import GLOBAL_CONFIG, Config, init_defualt_config
from src.api.redpacket import RedPacket, RedPacketType, RPSRedPacket, SpecifyRedPacket
from src.utils import (
Expand Down Expand Up @@ -79,6 +80,63 @@ def exec(self, api: FishPi, args: Tuple[str, ...]):
api.chatroom.siguoya()


class ArticleCommand(Command):
def __init__(self, article: Article = None) -> None:
self.curr_article = article

def exec(self, api: FishPi, args: Tuple[str, ...]):
lt = [i for i in args]
if len(lt) == 0:
article_list = api.article.list_articles()
api.article.format_article_list(article_list)

elif lt[0] == "page":
try:
page_index = int(lt[1])
article_list = api.article.list_articles(
page=page_index)
api.article.format_article_list(article_list)
except Exception:
print("参数错误,#article page {int}")

elif len(lt) > 1 and lt[0] == "view":
try:
article_index = int(lt[1])
if article_index <= 0:
print("页数必须大于0")
return
if 0 <= article_index < len(api.article.articles_oid()):
article = api.article.get_article(api.article.articles_oid(article_index))
article.get_content()
self.curr_article = article
api.article.format_comments_list(
article.get_articleComments())
print(f"\n[*** 当前帖子:{article.get_tittle()} ***]\n")

elif len(api.article.articles_oid()) < 1:
article_list = api.article.list_articles()
api.article.format_article_list(article_list)
article = api.article.get_article(api.article.articles_oid(article_index))
article.get_content()
self.curr_article = article
api.article.format_comments_list(
article.get_articleComments())
print(f"\n[*** 当前帖子:{article.get_tittle()} ***]\n")

else:
print("找不到对应编号或索引的文章")
except Exception:
print("参数错误,#article view {int}")

elif len(lt) > 1 and lt[0] == "comment":
comment_content = lt[1]

try:
api.article.comment_article(self.curr_article.oId, comment_content)
except Exception:
print("选择需要评论的帖子")


class AnswerMode(Command):
def exec(self, api: FishPi, args: Tuple[str, ...]):
if GLOBAL_CONFIG.chat_config.answer_mode:
Expand Down Expand Up @@ -379,6 +437,7 @@ def init_cli(api: FishPi):
cli_handler.add_command('#cli', EnterCil())
cli_handler.add_command('#chatroom', EnterChatroom())
cli_handler.add_command('#siguo', SiGuoYa())
cli_handler.add_command('#article', ArticleCommand())
cli_handler.add_command('#bm', BreezemoonsCommand())
cli_handler.add_command('#config', ConfigCommand())
cli_handler.add_command('#transfer', PointTransferCommand())
Expand Down
1 change: 1 addition & 0 deletions src/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
[#cli] 进入命令交互模式
[#chatroom] 进入聊天室模式
[#siguo] 思过崖
[#article] 看帖 (默认显示20个帖子) [view|page] {int} / 回帖 #article comment {str}
[#rp] 1 128 1个128积分 (默认5个,128积分)拼手气红包
[#rp-ave] 1 128 1个128积分 (默认5个,32积分)平均红包
[#rp-hb] 5 128 5个128积分 (默认5个,32积分)心跳红包
Expand Down
2 changes: 1 addition & 1 deletion src/utils/version.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# -*- coding: utf-8 -*-

__version__ = "2.0.4"
__version__ = "2.0.5"

0 comments on commit 4606b00

Please sign in to comment.