feat : 接入了noname的插件到bot(多线程运行)
This commit is contained in:
@@ -1,14 +1,32 @@
|
||||
from typing import Any, List
|
||||
|
||||
import botpy
|
||||
from botpy.message import Message
|
||||
from botpy.message import (Message)
|
||||
from botpy import logger
|
||||
import queue
|
||||
from dotenv import load_dotenv
|
||||
import os
|
||||
import types
|
||||
from bobby import bobbySession
|
||||
from mcwatcher import watcher
|
||||
from threading import Thread
|
||||
import asyncio
|
||||
#环境配置
|
||||
|
||||
class djtuWebsocket (botpy.Client) :
|
||||
async def on_group_at_message_create(self, message: Message):
|
||||
def __init__(
|
||||
self, intents: botpy.Intents,
|
||||
timeout: int = 5,
|
||||
is_sandbox=False,
|
||||
log_config: str | dict | None = None,
|
||||
log_format: str| None = None,
|
||||
log_level: int |None= None,
|
||||
bot_log: bool | None = True,
|
||||
ext_handlers: dict | List[dict] | bool = True):
|
||||
self.q = queue.Queue()
|
||||
super().__init__(intents, timeout, is_sandbox, log_config, log_format, log_level, bot_log, ext_handlers)
|
||||
|
||||
async def on_group_at_message_create(self, message: Message):
|
||||
await self.parseCommand(message)
|
||||
|
||||
async def on_group_message_create(self,message:Message):
|
||||
@@ -16,6 +34,7 @@ class djtuWebsocket (botpy.Client) :
|
||||
await self.parseGlobalMessage(message)
|
||||
|
||||
|
||||
# 触发概率不大所以可以直接提取关键字
|
||||
async def parseCommand(self,msg :Message):
|
||||
commands:dict[str,types.MethodType|types.FunctionType] = {
|
||||
r'/邀请码' : bobby.getInviteCode,
|
||||
@@ -34,17 +53,38 @@ class djtuWebsocket (botpy.Client) :
|
||||
reply = "你在发什么东西我怎么看不懂?"
|
||||
await msg.reply(content=reply)
|
||||
|
||||
# 触发概率大,以后要做好解析防止刷屏
|
||||
async def parseGlobalMessage(self,msg:Message):
|
||||
await msg.reply(content="awda")
|
||||
|
||||
# 监听队列,接受其他线程的消息
|
||||
async def mcloop(self):
|
||||
while True:
|
||||
if self.q.empty():
|
||||
# time.sleep会阻塞整个线程我去
|
||||
await asyncio.sleep(20)
|
||||
else:
|
||||
try :
|
||||
msg = self.q.get()
|
||||
if group_open_id is None:
|
||||
logger.error("群聊不存在")
|
||||
continue
|
||||
asyncio.create_task(self.api.post_group_message(group_open_id,content=msg))
|
||||
except Exception as e:
|
||||
logger.error("MCWatcher发送群聊任务失败:\n"+str(e))
|
||||
|
||||
# source
|
||||
load_dotenv(".env")
|
||||
print(os.getenv("APP_ID"))
|
||||
|
||||
|
||||
bbyAccount = os.getenv("BOBBY_ACCOUNT")
|
||||
bbyPasswd = os.getenv("BOBBY_PASSWORD")
|
||||
appid = os.getenv("APP_ID")
|
||||
secret_bot = os.getenv("SECRET")
|
||||
group_open_id = os.getenv("GROUP_OPEN_ID")
|
||||
|
||||
if appid is None or secret_bot is None :
|
||||
raise SystemExit("未找到bot配置!")
|
||||
logger.info("登录账号:"+appid)
|
||||
|
||||
# bobby Session
|
||||
if bbyAccount is None or bbyPasswd is None :
|
||||
@@ -53,6 +93,31 @@ if appid is None or secret_bot is None :
|
||||
raise SystemError("未找到bot配置")
|
||||
bobby = bobbySession(bbyAccount,bbyPasswd)
|
||||
|
||||
#bot 启动
|
||||
async def main(ws:djtuWebsocket, *args: Any, **kwargs: Any) -> None:
|
||||
async with ws as ws:
|
||||
logger.info("启动并发异步ing...")
|
||||
mcloop = ws.mcloop()
|
||||
# 你*的为什么retcoro true的话会报错啊
|
||||
# 协程对象不会不是这个异步回话而是httpx吧?
|
||||
bot = ws.start(*args, **kwargs,ret_coro=False)
|
||||
if bot is None:
|
||||
logger.error("bot不给协程啊")
|
||||
return
|
||||
try:
|
||||
await asyncio.gather(bot,mcloop)
|
||||
except Exception as e :
|
||||
logger.error(e)
|
||||
|
||||
# bot初始化
|
||||
ws = djtuWebsocket(botpy.Intents(public_messages=True))
|
||||
ws.run(appid=appid,secret=secret_bot)
|
||||
|
||||
# 启动mcwatcher线程
|
||||
def pushQuene(cont:str):
|
||||
ws.q.put(cont)
|
||||
Thread(target=watcher.MCWatcher,name="watcher",kwargs={
|
||||
"hookfunction":pushQuene,
|
||||
"logging":logger
|
||||
}).start()
|
||||
|
||||
# bot线程运行
|
||||
asyncio.run(main(ws,appid=appid,secret=secret_bot))
|
||||
|
||||
@@ -6,7 +6,7 @@ import re
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
from typing import Dict, Any, Optional, Set
|
||||
|
||||
import time
|
||||
import httpx
|
||||
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||||
|
||||
@@ -142,7 +142,7 @@ class MCWatcher:
|
||||
self.state.load()
|
||||
|
||||
self._stop = False
|
||||
self._task = asyncio.run(self._poll_loop())
|
||||
self._task = asyncio.run(self._poll_loop())
|
||||
# self._task = asyncio.create_task(self._poll_loop())
|
||||
|
||||
logger.info(
|
||||
@@ -154,7 +154,7 @@ class MCWatcher:
|
||||
if self._task:
|
||||
self._task.cancel()
|
||||
# try:
|
||||
# # await self._task
|
||||
# await self._task
|
||||
# except asyncio.CancelledError:
|
||||
# pass
|
||||
self.state.save()
|
||||
@@ -243,6 +243,9 @@ class MCWatcher:
|
||||
# ========== 轮询 ==========
|
||||
|
||||
async def _poll_loop(self):
|
||||
logger.info("等待bot完毕~")
|
||||
# 防止bot未初始化
|
||||
time.sleep(10)
|
||||
try:
|
||||
await self._check_once(force_push=False)
|
||||
except Exception as e:
|
||||
@@ -353,4 +356,4 @@ class MCWatcher:
|
||||
|
||||
# logger.info(f"{_ts()} MCWatcher 已推送 {ok}/{len(targets)} 个会话。")
|
||||
async def _broadcast(self, text: str, targets: Set[str]):
|
||||
self.hookfunction.__call__(text,targets)
|
||||
self.hookfunction(text)
|
||||
@@ -1,3 +1,4 @@
|
||||
requests
|
||||
qq-botpy
|
||||
dotenv
|
||||
httpx
|
||||
Reference in New Issue
Block a user