Compare commits

...
8 Commits
Author SHA1 Message Date
Wbucket 87551ee358 fix : 忘记存储群组了QAQ 2026-09-30 23:00:53 +08:00
Wbucket 99acbf6cc9 fix : 全量覆盖@消息(十分蹩脚的方式) 2026-09-30 22:09:26 +08:00
Wbucket 9e46704d63 feat : 群组记录存储 && .gitingore 2026-09-30 22:08:14 +08:00
Wbucket 9cb81deab4 feat : mcwatcher 广播 2026-09-30 21:18:03 +08:00
Wbucket 3d5ee01873 feat : 全局消息监听 2026-09-30 18:39:25 +08:00
Wbucket 5db01d429d fix : 移除dev 2026-09-30 16:23:55 +08:00
Wbucket cac4856f2f fix : 暂时添加dev变量 2026-09-30 13:28:33 +08:00
Wbucket f7ad06c085 feat : 入群消息和自定事件触发接口 2026-09-30 13:21:45 +08:00
3 changed files with 253 additions and 123 deletions
+4
View File
@@ -173,3 +173,7 @@ cython_debug/
# PyPI configuration file # PyPI configuration file
.pypirc .pypirc
.*
state.json
botpy.log*
joined_group.cfg
+227 -123
View File
@@ -1,123 +1,227 @@
from typing import Any, List from typing import Any, List
import group
import botpy
from botpy.message import (Message) from botpy.connection import ConnectionSession
from botpy import logger from botpy.message import (Message,GroupMessage)
import queue from botpy.flags import (Flag,fill_with_flags)
from dotenv import load_dotenv from botpy import( logger,Intents,Client)
import os from botpy.gateway import (BotWebSocket)
import types from botpy.types.gateway import MessagePayload
from bobby import bobbySession import queue
from mcwatcher import watcher from botpy.types.session import Session
from threading import Thread from dotenv import load_dotenv
import asyncio import os
#环境配置 import types
from bobby import bobbySession
class djtuWebsocket (botpy.Client) : from mcwatcher import watcher
def __init__( from threading import Thread
self, intents: botpy.Intents, import asyncio
timeout: int = 5, #环境配置
is_sandbox=False,
log_config: str | dict | None = None, class Intents_ex(Intents):
log_format: str| None = None, def __init__(self, **kwargs: bool) -> None:
log_level: int |None= None, arg_tmp = dict[str,bool]()
bot_log: bool | None = True, arg_ex = dict[str,bool]()
ext_handlers: dict | List[dict] | bool = True): for key, value in kwargs.items():
self.q = queue.Queue() if key in ['member_event']:
super().__init__(intents, timeout, is_sandbox, log_config, log_format, log_level, bot_log, ext_handlers) arg_ex[key] = value
else:
async def on_group_at_message_create(self, message: Message): arg_tmp[key] = value
await self.parseCommand(message)
super().__init__(**arg_tmp)
async def on_group_message_create(self,message:Message): for key , value in arg_ex.items() :
setattr(self, key, value)
await self.parseGlobalMessage(message)
@Flag
def member_event(self):
# 触发概率不大所以可以直接提取关键字 return 1 << 24
async def parseCommand(self,msg :Message):
commands:dict[str,types.MethodType|types.FunctionType] = { class BotWebsocket_ex(BotWebSocket):
r'/邀请码' : bobby.getInviteCode, def __init__(self, session: Session, _connection: ConnectionSession):
r'吃什么' : lambda :"是啊吃什么" super().__init__(session, _connection)
} self._parser['group_member_add'] = lambda aaw:self._connection.dispatch("group_member_add",aaw)
required = msg.content self._parser['group_message_create'] = lambda aaw:self._connection.dispatch("group_message_create",aaw)
reply = ""
for cmd,func in commands.items(): class djtuWebsocket (Client) :
if required.find(cmd) != -1: def __init__(
try: self, intents: Intents,
reply = func() timeout: int = 5,
except: is_sandbox=False,
reply = "服务异常" log_config: str | dict | None = None,
break log_format: str| None = None,
if reply.__len__() == 0: log_level: int |None= None,
reply = "你在发什么东西我怎么看不懂?" bot_log: bool | None = True,
await msg.reply(content=reply) 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 parseGlobalMessage(self,msg:Message):
# await msg.reply(content="awda")
# 监听队列,接受其他线程的消息 async def bot_connect(self, session):
async def mcloop(self): """
while True: newConnect 启动一个新的连接,如果连接在监听过程中报错了,或者被远端关闭了链接,需要识别关闭的原因,能否继续 resume
if self.q.empty(): 如果能够 resume,则往 sessionChan 中放入带有 sessionID 的 session
# time.sleep会阻塞整个线程我去 如果不能,则清理掉 sessionID,将 session 放入 sessionChan 中
await asyncio.sleep(20) session 的启动,交给 start 中的 for 循环执行,session 不自己递归进行重连,避免递归深度过深
else:
try : param session: session对象
msg = self.q.get() """
if group_open_id is None: logger.info("[botpy] 会话启动中...")
logger.error("群聊不存在")
continue client = BotWebsocket_ex(session, self._connection)
asyncio.create_task(self.api.post_group_message(group_open_id,content=msg)) try:
except Exception as e: await client.ws_connect()
logger.error("MCWatcher发送群聊任务失败:\n"+str(e)) except (Exception, KeyboardInterrupt, SystemExit) as e:
await client.on_error(e)
# source
load_dotenv(".env") async def on_group_at_message_create(self, message: Message):
await self.parseCommand(message)
bbyAccount = os.getenv("BOBBY_ACCOUNT")
bbyPasswd = os.getenv("BOBBY_PASSWORD") async def on_group_message_create(self,message):
appid = os.getenv("APP_ID") # 检验是否有自身@消息
secret_bot = os.getenv("SECRET") try:
group_open_id = os.getenv("GROUP_OPEN_ID") msg = message['d']
mention = msg['mentions']
if appid is None or secret_bot is None : for m in mention :
raise SystemExit("未找到bot配置!") if m['is_you'] == True:
logger.info("登录账号:"+appid) return await self.parseCommand(GroupMessage(self.api,msg['id'],MessagePayload(message['d'])))
except:
# bobby Session '没有@消息欸'
if bbyAccount is None or bbyPasswd is None :
raise SystemError("未找到账密配置") return await self.parseGlobalMessage(message)
if appid is None or secret_bot is None :
raise SystemError("未找到bot配置")
bobby = bobbySession(bbyAccount,bbyPasswd) async def on_group_member_add(self,payload):
# await message.reply(content="awdwa")
async def main(ws:djtuWebsocket, *args: Any, **kwargs: Any) -> None: openid = 'null'
async with ws as ws: memberid = 'null'
logger.info("启动并发异步ing...") eid ='null'
mcloop = ws.mcloop() try :
# 你*的为什么retcoro true的话会报错啊 eid = payload['id']
# 协程对象不会不是这个异步回话而是httpx吧? data = payload['d']
bot = ws.start(*args, **kwargs,ret_coro=False) openid = data['group_openid']
if bot is None: memberid = data['member_openid']
logger.error("bot不给协程啊") except:
return logger.warning("data解析失败")
try: return
await asyncio.gather(bot,mcloop) logger.info("入群信息:"+' 群: '+openid+" openid: "+memberid)
except Exception as e : await self.api.post_group_message(openid,event_id=eid,content='欢迎加入大海啸!\n入服教程请看链接:\nhttps://starptr.top')
logger.error(e)
# 触发概率不大所以可以直接提取关键字
# bot初始化 async def parseCommand(self,msg :Message):
ws = djtuWebsocket(botpy.Intents(public_messages=True)) commands:dict[str,types.MethodType|types.FunctionType] = {
r'/邀请码' : bobby.getInviteCode,
# 启动mcwatcher线程 r'吃什么' : lambda :"是啊吃什么"
def pushQuene(cont:str): }
ws.q.put(cont) required = msg.content
Thread(target=watcher.MCWatcher,name="watcher",kwargs={ reply = ""
"hookfunction":pushQuene, for cmd,func in commands.items():
"logging":logger if required.find(cmd) != -1:
}).start() try:
reply = func()
# bot线程运行 except:
asyncio.run(main(ws,appid=appid,secret=secret_bot)) reply = "服务异常"
break
if reply.__len__() == 0:
reply = "你在发什么东西我怎么看不懂?"
await msg.reply(content=reply)
# 触发概率大,以后要做好解析防止刷屏
async def parseGlobalMessage(self,payload):
try :
msg = payload['d']
gid = msg['group_id']
content = msg['content']
except:
return
# 加入群聊
new_group = True
if not groups is None :
for i in groups.groups :
if i.find(gid) != -1 :
new_group = False
if new_group :
groups.groups.append(gid)
groups.save()
# 解析指令
commands:dict[str,types.MethodType|types.FunctionType] = {
r'吃什么' : lambda :"是啊吃什么"
}
required = content
reply = ""
for cmd,func in commands.items():
if required.find(cmd) != -1:
try:
reply = func()
except:
reply = "服务异常"
break
if reply.__len__() == 0:
return
await self.api.post_group_message(gid,content=reply)
# 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()
for i in groups.groups:
asyncio.create_task(self.api.post_group_message(i,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")
groups = group.GroupCtl()
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(Intents_ex(public_messages=True,member_event=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))
+22
View File
@@ -0,0 +1,22 @@
import os
# 记录加入的群组
class GroupCtl :
path = os.path.join(os.getcwd(),"joined_group.cfg")
groups:list[str] = []
def __init__(self) -> None:
with open(self.openfile()) as awa:
self.groups = awa.readlines()
def save(self):
# 重新加载
fd = self.openfile()
os.truncate(self.path,0)
os.write(fd,bytes('\n'.join(self.groups),'utf-8'))
os.close(fd)
def openfile(self):
return os.open(self.path,os.O_RDWR|os.O_CREAT)