Skip to content

Commit

Permalink
feat: 优化重复解析 #28
Browse files Browse the repository at this point in the history
  • Loading branch information
mengshouer committed Sep 23, 2024
1 parent ff82f2d commit 1e6a90c
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 8 deletions.
25 changes: 25 additions & 0 deletions nonebot_plugin_analysis_bilibili/ExpiringCache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import threading


class ExpiringCache:
def __init__(self, expire_seconds=60):
self.cache = set()
self.expire_seconds = expire_seconds

def set(self, value):
if value in self.cache:
return
self.cache.add(value)
threading.Timer(self.expire_seconds, self._expire, args=(value,)).start()

def _expire(self, value):
if value in self.cache:
self.cache.remove(value)

def get(self, value):
if value in self.cache:
return value
return None

def __str__(self):
return str(self.cache)
17 changes: 10 additions & 7 deletions nonebot_plugin_analysis_bilibili/analysis_bilibili.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@
from typing import Dict, List, Optional, Tuple, Union
from aiohttp import ClientSession

from .ExpiringCache import ExpiringCache
from .wbi import get_query

# analysis_stat : {group_id: ExpiringCache}
analysis_stat: Dict[int, ExpiringCache] = {}

# group_id : [last_vurl, last_analysis_time]
analysis_stat: Dict[int, List] = {}

config = nonebot.get_driver().config
analysis_display_image = getattr(config, "analysis_display_image", False)
Expand Down Expand Up @@ -58,12 +59,14 @@ async def bili_keyword(

# 避免多个机器人解析重复推送
if group_id:
if group_id in analysis_stat and analysis_stat[group_id][0] == vurl:
if not reanalysis_time or analysis_stat[group_id][1] + int(
reanalysis_time
) > int(time()):
if group_id in analysis_stat:
if analysis_stat[group_id].get(vurl):
return False
analysis_stat[group_id] = [vurl, int(time())]
analysis_stat[group_id].set(vurl)
else:
analysis_stat[group_id] = ExpiringCache(expire_seconds=reanalysis_time)
analysis_stat[group_id].set(vurl)

except Exception as e:
msg = "bili_keyword Error: {}".format(type(e))
return msg
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "nonebot-plugin-analysis-bilibili"
version = "2.7.4"
version = "2.7.5"
description = "nonebot2解析bilibili插件"
authors = ["mengshouer"]
license = "MIT"
Expand Down

0 comments on commit 1e6a90c

Please sign in to comment.