Skip to content

Commit

Permalink
Merge pull request #97 from AmiyaBot/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
vivien8261 authored Jun 17, 2024
2 parents f5d193b + c495c10 commit a546d95
Show file tree
Hide file tree
Showing 10 changed files with 153 additions and 108 deletions.
5 changes: 4 additions & 1 deletion amiyabot/adapters/onebot/v11/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,12 @@ async def append_voice(file: str):


def send_msg(chain: Chain, chain_data: Union[str, list]):
return {
msg_data = {
'message_type': chain.data.message_type,
'user_id': chain.data.user_id,
'group_id': chain.data.channel_id,
'message': chain_data,
}
msg_data = {k: v for k, v in msg_data.items() if v is not None and v != ''}

return msg_data
53 changes: 53 additions & 0 deletions amiyabot/adapters/tencent/intents.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
"""
https://bot.q.qq.com/wiki/develop/api-v2/dev-prepare/interface-framework/event-emit.html#websocket-%E6%96%B9%E5%BC%8F
"""
import enum


class IntentsClass(enum.Enum):
@classmethod
def calc(cls):
intent = 0
for item in cls:
intent |= item.value
return intent


class CommonIntents(IntentsClass):
GUILDS = 1 << 0
GUILD_MEMBERS = 1 << 1
GUILD_MESSAGE_REACTIONS = 1 << 10
DIRECT_MESSAGE = 1 << 12
INTERACTION = 1 << 26
MESSAGE_AUDIT = 1 << 27
AUDIO_ACTION = 1 << 29


class PublicIntents(IntentsClass):
PUBLIC_GUILD_MESSAGES = 1 << 30


class PrivateIntents(IntentsClass):
GUILD_MESSAGES = 1 << 9
FORUMS_EVENT = 1 << 28


class GroupIntents(IntentsClass):
GROUP_AND_C2C_EVENT = 1 << 25


def get_intents(private: bool, name: str) -> int:
if name == 'QQGroup':
return GroupIntents.calc()

res = CommonIntents.calc()

if private:
res |= PrivateIntents.calc()
else:
res |= PublicIntents.calc()

if name == 'QQGlobal':
res |= GroupIntents.calc()

return res
27 changes: 27 additions & 0 deletions amiyabot/adapters/tencent/qqGlobal/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from amiyabot.builtin.messageChain import Chain, ChainBuilder
from amiyabot.adapters.tencent.qqGuild import QQGuildBotInstance
from amiyabot.adapters.tencent.qqGroup import QQGroupBotInstance

from .package import package_qq_global_message


class QQGlobalBotInstance(QQGroupBotInstance):
def __init__(self, appid: str, token: str, client_secret: str, default_chain_builder: ChainBuilder):
super().__init__(appid, token, client_secret, default_chain_builder)

self.guild = QQGuildBotInstance(appid, token)

def __str__(self):
return 'QQGlobal'

@property
def package_method(self):
return package_qq_global_message

async def send_chain_message(self, chain: Chain, is_sync: bool = False):
if not (chain.data.channel_openid or chain.data.user_openid):
return await self.guild.send_chain_message(chain, is_sync)
return await super().send_chain_message(chain, is_sync)


qq_global = QQGlobalBotInstance.build_adapter
20 changes: 20 additions & 0 deletions amiyabot/adapters/tencent/qqGlobal/package.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from amiyabot.adapters import BotAdapterProtocol
from amiyabot.adapters.tencent.qqGroup.package import package_qq_group_message
from amiyabot.adapters.tencent.qqGuild.package import package_qq_guild_message


async def package_qq_global_message(
instance: BotAdapterProtocol,
event: str,
message: dict,
is_reference: bool = False,
):
group_message_created = [
'C2C_MESSAGE_CREATE',
'GROUP_AT_MESSAGE_CREATE',
]

if event in group_message_created:
return await package_qq_group_message(instance, event, message, is_reference)

return await package_qq_guild_message(instance, event, message, is_reference)
51 changes: 31 additions & 20 deletions amiyabot/adapters/tencent/qqGroup/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from typing import Optional
from amiyabot.builtin.messageChain import Chain, ChainBuilder
from amiyabot.adapters import HANDLER_TYPE
from amiyabot.adapters.tencent.qqGuild import QQGuildBotInstance

from .api import QQGroupAPI, log
Expand All @@ -13,23 +14,6 @@
build_message_send,
)
from .package import package_qq_group_message
from ... import HANDLER_TYPE


def qq_group(
client_secret: str,
default_chain_builder: Optional[ChainBuilder] = None,
default_chain_builder_options: QQGroupChainBuilderOptions = QQGroupChainBuilderOptions(),
):
def adapter(appid: str, token: str):
if default_chain_builder:
cb = default_chain_builder
else:
cb = QQGroupChainBuilder(default_chain_builder_options)

return QQGroupBotInstance(appid, token, client_secret, cb)

return adapter


class QQGroupBotInstance(QQGuildBotInstance):
Expand All @@ -43,6 +27,23 @@ def __init__(self, appid: str, token: str, client_secret: str, default_chain_bui
def __str__(self):
return 'QQGroup'

@classmethod
def build_adapter(
cls,
client_secret: str,
default_chain_builder: Optional[ChainBuilder] = None,
default_chain_builder_options: QQGroupChainBuilderOptions = QQGroupChainBuilderOptions(),
):
def adapter(appid: str, token: str):
if default_chain_builder:
cb = default_chain_builder
else:
cb = QQGroupChainBuilder(default_chain_builder_options)

return cls(appid, token, client_secret, cb)

return adapter

@property
def api(self):
return self.__access_token_api
Expand Down Expand Up @@ -74,10 +75,20 @@ async def send_chain_message(self, chain: Chain, is_sync: bool = False):
for payload in payloads:
async with log.catch('post error:', ignore=[asyncio.TimeoutError]):
res.append(
await self.api.post_group_message(
chain.data.channel_openid,
payload,
await (
self.api.post_private_message(
chain.data.user_openid,
payload,
)
if chain.data.is_direct
else self.api.post_group_message(
chain.data.channel_openid,
payload,
)
)
)

return [QQGroupMessageCallback(chain.data, self, item) for item in res]


qq_group = QQGroupBotInstance.build_adapter
3 changes: 3 additions & 0 deletions amiyabot/adapters/tencent/qqGroup/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,6 @@ async def upload_file(self, channel_openid: str, file_type: int, url: str, srv_s

async def post_group_message(self, channel_openid: str, payload: dict):
return await self.post(f'/v2/groups/{channel_openid}/messages', payload)

async def post_private_message(self, user_openid: str, payload: dict):
return await self.post(f'/v2/users/{user_openid}/messages', payload)
12 changes: 8 additions & 4 deletions amiyabot/adapters/tencent/qqGroup/package.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,15 @@ async def package_qq_group_message(instance: BotAdapterProtocol, event: str, mes
data.is_direct = event == 'C2C_MESSAGE_CREATE'
data.is_at = True

data.user_id = message['author']['id']
data.user_openid = message['author']['member_openid']
data.channel_id = message['group_id']
data.channel_openid = message['group_openid']
data.message_id = message['id']
data.user_id = message['author']['id']

if data.is_direct:
data.user_openid = message['author']['user_openid']
else:
data.user_openid = message['author']['member_openid']
data.channel_id = message['group_id']
data.channel_openid = message['group_openid']

if 'attachments' in message:
for item in message['attachments']:
Expand Down
7 changes: 4 additions & 3 deletions amiyabot/adapters/tencent/qqGuild/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
from amiyabot.builtin.message import Message
from amiyabot.builtin.messageChain import Chain
from amiyabot.adapters import BotAdapterProtocol, HANDLER_TYPE
from amiyabot.adapters.tencent.intents import get_intents

from .api import QQGuildAPI, log
from .model import GateWay, Payload, ShardsRecord, ConnectionHandler
from .intents import get_intents
from .package import package_qq_guild_message
from .builder import build_message_send, QQGuildMessageCallback

Expand Down Expand Up @@ -91,7 +91,8 @@ async def create_connection(self, handler: ConnectionHandler, shards_index: int
if payload.t == 'READY':
self.bot_name = payload.d['user']['username']
log.info(
f'connected({sign}): {self.bot_name}(%s)' % ('private' if handler.private else 'public')
f'connected({sign}): {self.bot_name}({self}-%s)'
% ('private' if handler.private else 'public')
)
self.shards_record[shards_index].session_id = payload.d['session_id']

Expand All @@ -104,7 +105,7 @@ async def create_connection(self, handler: ConnectionHandler, shards_index: int
if payload.op == 10:
create_token = {
'token': f'Bot {self.appid}.{self.token}',
'intents': get_intents(handler.private, self.__str__()).get_all_intents(),
'intents': get_intents(handler.private, self.__str__()),
'shard': [shards_index, gateway.shards],
'properties': {
'$os': sys.platform,
Expand Down
77 changes: 0 additions & 77 deletions amiyabot/adapters/tencent/qqGuild/intents.py

This file was deleted.

6 changes: 3 additions & 3 deletions amiyabot/builtin/message/structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,14 @@ def __str__(self):
face = ''.join([f'[face:{n}]' for n in self.face])
image = '[image]' * len(self.image)

return 'Bot:{bot} Channel:{channel} User:{user}{admin}{direct} {nickname}: {message}'.format(
return 'Bot:{bot}{channel} User:{user}{admin}{direct}{nickname}: {message}'.format(
**{
'bot': self.instance.appid,
'channel': self.channel_id,
'channel': f' Channel:{self.channel_id}' if self.channel_id else '',
'user': self.user_id,
'admin': '(admin)' if self.is_admin else '',
'direct': '(direct)' if self.is_direct else '',
'nickname': self.nickname,
'nickname': f' {self.nickname}' if self.nickname else '',
'message': text + face + image,
}
)
Expand Down

0 comments on commit a546d95

Please sign in to comment.