from typing import Any, List import botpy 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) : 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): await self.parseGlobalMessage(message) # 触发概率不大所以可以直接提取关键字 async def parseCommand(self,msg :Message): commands:dict[str,types.MethodType|types.FunctionType] = { r'/邀请码' : bobby.getInviteCode, r'吃什么' : lambda :"是啊吃什么" } required = msg.content reply = "" for cmd,func in commands.items(): if required.find(cmd) != -1: try: reply = func() except: reply = "服务异常" break if reply.__len__() == 0: 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") 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 : raise SystemError("未找到账密配置") if appid is None or secret_bot is None : raise SystemError("未找到bot配置") bobby = bobbySession(bbyAccount,bbyPasswd) 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)) # 启动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))