Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
9564cb2
feat: 完善ws事件中Message数据的构建
GLGDLY Jun 16, 2022
8eafc07
Merge remote-tracking branch 'origin/master'
GLGDLY Jun 16, 2022
109c74e
feat: 完善ws事件中User-Member数据的构建
GLGDLY Jun 16, 2022
26af7ad
feat: 完善ws事件中Reaction、Audio、DirectMessage 以及 Forum(Thread类)数据的构建
GLGDLY Jun 16, 2022
6cc4e6d
feat: 完善ws事件中监听文档并优化格式
GLGDLY Jun 17, 2022
840ae51
fix: forum thread的事件数据名称更变后同步数据更改到其他文件
GLGDLY Jun 17, 2022
9b92ad5
refactor: 优化ext下的扩展工具
SaucePlum Jun 17, 2022
b071d4a
Merge branch 'tencent-connect:master' into master
SaucePlum Jun 17, 2022
8ec0874
refactor: 优化ext的convert_color模块
GLGDLY Jun 17, 2022
15d2dc2
refactor: 优化ext下的扩展工具
SaucePlum Jun 17, 2022
f802ef8
refactor: 优化ext下的扩展工具
SaucePlum Jun 17, 2022
c485a43
docs: 修改一处表述不正确的地方
SaucePlum Jun 18, 2022
2efa199
Merge branch 'tencent-connect:master' into master
SaucePlum Jun 20, 2022
2609dd3
feat: 修改一处表述不正确的地方
SaucePlum Jun 21, 2022
d409241
Merge remote-tracking branch 'origin/master'
SaucePlum Jun 21, 2022
5e7f598
fix: 帖子api中route方式错误的问题
SaucePlum Jun 23, 2022
3db66ac
feat: 补齐频道成员中的删除频道成员api
SaucePlum Jun 23, 2022
460ba10
feat: 更新文档并新增定时框架
SaucePlum Jun 24, 2022
42dd743
Merge branch 'tencent-connect:master' into master
SaucePlum Jun 24, 2022
406944f
fix: 修复Member构建的部分字段取值错误的问题
SaucePlum Jun 25, 2022
81d53f7
docs: 更新botpy文档
SaucePlum Jun 25, 2022
ecf6988
fix: 修复删除频道成员API无法拉黑的问题
SaucePlum Jun 25, 2022
de80c35
fix: rst文件回滚
SaucePlum Jun 25, 2022
dc10a76
feat: 为http请求成功添加trace_id
SaucePlum Jun 27, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
153 changes: 24 additions & 129 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,25 @@
# botpy
<div align="center">

**botpy** 是基于[机器人开放平台API](https://bot.q.qq.com/wiki/develop/api/) 实现的机器人框架,目的提供一个易使用、开发效率高的开发框架。
![botpy](https://socialify.git.ci/tencent-connect/botpy/image?description=1&font=Source%20Code%20Pro&forks=1&issues=1&language=1&logo=https%3A%2F%2Fgithub.com%2Ftencent-connect%2Fbot-docs%2Fblob%2Fmain%2Fdocs%2F.vuepress%2Fpublic%2Ffavicon-64px.png%3Fraw%3Dtrue&owner=1&pattern=Circuit%20Board&pulls=1&stargazers=1&theme=Light)

[![Language](https://img.shields.io/badge/language-python-green.svg?style=plastic)](https://www.python.org/)
[![License](https://img.shields.io/badge/license-MIT-orange.svg?style=plastic)](https://github.com/tencent-connect/botpy/blob/master/LICENSE)
![Python](https://img.shields.io/badge/python-3.8+-blue)
![PyPI](https://img.shields.io/pypi/v/qq-botpy)
[![BK Pipelines Status](https://api.bkdevops.qq.com/process/api/external/pipelines/projects/qq-guild-open/p-713959939bdc4adca0eea2d4420eef4b/badge?X-DEVOPS-PROJECT-ID=qq-guild-open)](https://devops.woa.com/process/api-html/user/builds/projects/qq-guild-open/pipelines/p-713959939bdc4adca0eea2d4420eef4b/latestFinished?X-DEVOPS-PROJECT-ID=qq-guild-open)

_✨ 基于 [机器人开放平台API](https://bot.q.qq.com/wiki/develop/api/) 实现的机器人框架 ✨_

_✨ 为开发者提供一个易使用、开发效率高的开发框架 ✨_

[文档](https://bot.q.qq.com/wiki/develop/pythonsdk/)
·
[下载](https://github.com/tencent-connect/botpy/tags)
·
[安装](https://bot.q.qq.com/wiki/develop/pythonsdk/#sdk-安装)

</div>

## 准备工作

### 安装
Expand Down Expand Up @@ -43,12 +58,9 @@ import botpy

```python
import botpy
from botpy.types.message import Message
from botpy.message import Message

class MyClient(botpy.Client):
async def on_ready(self):
print(f"robot 「{self.robot.name}」 on_ready!")

async def on_at_message_create(self, message: Message):
await message.reply(content=f"机器人{self.robot.name}收到你的@消息了: {message.content}")
```
Expand All @@ -61,7 +73,7 @@ class MyClient(botpy.Client):

```python
import botpy
from botpy.types.message import Message
from botpy.message import Message

class MyClient(botpy.Client):
async def on_at_message_create(self, message: Message):
Expand Down Expand Up @@ -89,7 +101,7 @@ intents.public_guild_messages=True

```python
import botpy
from botpy.types.message import Message
from botpy.message import Message

class MyClient(botpy.Client):
async def on_at_message_create(self, message: Message):
Expand Down Expand Up @@ -122,125 +134,6 @@ class MyClient(botpy.Client):
├── demo_recall.py # 机器人消息撤回示例
├── demo_schedule.py # 机器人日程相关示例

## 日志打印

基于自带的 logging 模块封装的日志模块,提供了日志写入以及美化了打印格式,并支持调整打印级别(默认打印级别为 `INFO`)。

### 使用方法

引用模块,并获取 `logger` 实例:

```python
from botpy import logging

logger = logging.get_logger()
```

或者通过`botpy.logger`也可以获取logger对象

然后就可以愉快地使用 logger 进行打印。例如:

```python
logger.info("hello world!")
```

### 日志设置

SDK的日志设置集成在`bot.Client`的实例化阶段,也可通过[`logging.configure_logging`](botpy/logging.py)修改(均为可选)

```python
import botpy

# 示例,非默认值
botpy.Client(
log_level=10,
log_format="new format",
bot_log=None,
ext_handlers=False,
log_config="log_config.json"
)

```

### log_level

日志级别,默认为`INFO`

命令行启动py可增加参数`-d` 或 `--debug`快捷打开debug日志

```bash
python3 demo_at_reply.py -d
```

几个可选取值(参考了[logging模块的取值](https://docs.python.org/3/library/logging.html#levels)):

| Level | 取值 |
| -------- | --- |
| CRITICAL | 50 |
| ERROR | 40 |
| WARNING | 30 |
| INFO | 20 |
| DEBUG | 10 |
| NOTSET | 0 |

### log_format

日志控制台输出格式,默认为 `"\033[1;33m[%(levelname)s]\t(%(filename)s:%(lineno)s)%(funcName)s\t\033[0m%(message)s"`

### bot_log

是否启用`botpy`日志,默认为`True`

`True` 启用
`None` 禁用 拓展
`False` 禁用 拓展+控制台输出

### ext_handlers

日志Handler拓展,为`True`使用默认拓展,`False`不添加拓展,可用list添加多个拓展。默认为`True`

[默认拓展](./botpy/logging.py)

```python
import os
import logging
from logging.handlers import TimedRotatingFileHandler

DEFAULT_FILE_HANDLER = {
# 要实例化的Handler
"handler": TimedRotatingFileHandler,
# 可选 Default to DEFAULT_FILE_FORMAT
"format": "%(asctime)s\t[%(levelname)s]\t(%(filename)s:%(lineno)s)%(funcName)s\t%(message)s",
# 可选 Default to DEBUG
"level": logging.DEBUG,
# 以下是Handler相关参数
"when": "D",
"backupCount": 7,
"encoding": "utf-8",
# *特殊* 对于filename参数,其中如有 %(name)s 会在实例化阶段填入相应的日志name
"filename": os.path.join(os.getcwd(), "%(name)s.log"),
}
```

#### 修改默认拓展

```python
import os
import botpy
from botpy.logging import DEFAULT_FILE_HANDLER

# 修改日志路径
DEFAULT_FILE_HANDLER["filename"] = os.path.join(os.getcwd(), "log", "%(name)s.log")
# 修改日志格式
DEFAULT_FILE_HANDLER["format"] = "new format"

botpy.Client(ext_handlers=DEFAULT_FILE_HANDLER)
```

### log_config

该参数将传入`logging.config.dictConfig`(内置logging而非botpy.logging),如果为.json/.yaml文件路径将从文件中读取配置,无默认值

# 参与开发

## 环境配置
Expand Down Expand Up @@ -271,9 +164,11 @@ pytest

## 致谢

感谢参与内测、开发和提出宝贵意见的开发者们(排名不分先后)
感谢感谢以下开发者对 `botpy` 作出的贡献

[小念](https://github.com/ReadSmall), [Neutron](https://github.com/Huang1220), [晚柒载](https://github.com/wqzai)
<a href="https://github.com/tencent-connect/botpy/graphs/contributors">
<img src="https://contrib.rocks/image?repo=tencent-connect/botpy" />
</a>

# 加入官方社区

Expand Down
8 changes: 4 additions & 4 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ botpy

..

原机器人的老版本\ ``qq-bot``\ 仍然可以使用,但新接口的支持上会逐渐暂停,此次升级不会影响线上使用的机器人
原机器人的老版本\ ``qq-bot``\ 仍然可以使用,但新接口的支持上会逐渐暂停,此次升级不会影响线上使用的机器人


使用方式
Expand All @@ -56,7 +56,7 @@ botpy
步骤1
~~~~~

通过继承实现\ ``bot.Client``\ , 实现自己的机器人Client
通过继承实现\ ``bot.Client``\ , 实现自己的机器人Client

步骤2
~~~~~
Expand Down Expand Up @@ -93,7 +93,7 @@ botpy
async def on_at_message_create(self, message: Message):
await self.api.post_message(channel_id=message.channel_id, content="content")

intents = botpy.Intents(public_guild_messages=True)
intents = botpy.Intents(public_guild_messages=True)
client = MyClient(intents=intents)
client.run(appid="12345", token="xxxx")

Expand Down Expand Up @@ -126,7 +126,7 @@ botpy
示例机器人
----------

`\ ``examples`` <./examples/>`_ 目录下存放示例机器人,具体使用可参考\ `\ ``Readme.md`` <./examples/README.md>`_
`\ ``examples`` <./examples/>`_ 目录下存放示例机器人,具体使用可参考\ `\ ``Readme.md`` <./examples/README.md>`_

.. code-block::

Expand Down
6 changes: 3 additions & 3 deletions botpy/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,14 +216,14 @@ async def get_delete_member(
# 注:消息撤回时间范围仅支持固定的天数:3,7,15,30。 特殊的时间范围:-1: 撤回全部消息。默认值为0不撤回任何消息。
if delete_history_msg_days not in (3, 7, 15, 30, 0, -1):
delete_history_msg_days = 0
params = {'add_blacklist': str(add_blacklist).lower(), 'delete_history_msg_days': delete_history_msg_days}
payload = {"add_blacklist": add_blacklist, "delete_history_msg_days": delete_history_msg_days}
route = Route(
"DELETE",
"/guilds/{guild_id}/members/{user_id}",
guild_id=guild_id,
user_id=user_id,
)
return await self._http.request(route, params=params)
return await self._http.request(route, json=payload)

async def get_guild_members(self, guild_id: str, after: str = "0", limit: int = 1) -> List[user.Member]:
"""
Expand Down Expand Up @@ -268,7 +268,7 @@ async def get_voice_members(self, channel_id: str) -> List[user.Member]:
# 子频道相关接口
async def get_channel(self, channel_id: str) -> channel.ChannelPayload:
"""
它获取频道信息。
获取频道信息

Args:
channel_id (str): 子频道 ID。
Expand Down
13 changes: 13 additions & 0 deletions botpy/ext/cog_apscheduler/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# -*- coding: utf-8 -*-

from botpy import logging

from apscheduler.schedulers.asyncio import AsyncIOScheduler

_log = logging.get_logger()

scheduler = AsyncIOScheduler()
scheduler.configure({"apscheduler.timezone": "Asia/Shanghai"})

scheduler.start()
_log.debug("[加载插件] APScheduler 定时任务")
2 changes: 1 addition & 1 deletion botpy/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ async def _handle_response(url, response: ClientResponse) -> Union[Dict[str, Any
except (KeyError, JSONDecodeError):
data = None
if response.status in HTTP_OK_STATUS:
_log.debug(f"[botpy] 请求成功, 请求连接: {url}, 返回内容: {data}")
_log.debug(f"[botpy] 请求成功, 请求连接: {url}, 返回内容: {data}, trace_id:{response.headers.get(X_TPS_TRACE_ID)}")
return data
else:
_log.error(
Expand Down
11 changes: 2 additions & 9 deletions botpy/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,7 @@


class Member:
__slots__ = (
"_api",
"_ctx",
"user",
"nick",
"roles",
"joined_at",
"event_id")
__slots__ = ("_api", "_ctx", "user", "nick", "roles", "joined_at", "event_id")

def __init__(self, api: BotAPI, ctx: gateway.WsContext, data: user.GuildMemberPayload):
self._api = api
Expand All @@ -23,7 +16,7 @@ def __init__(self, api: BotAPI, ctx: gateway.WsContext, data: user.GuildMemberPa

class _User:
def __init__(self, data):
self.id = data.get("user")
self.id = data.get("id")
self.username = data.get("username")
self.avatar = data.get("avatar")
self.bot = data.get("bot")
Expand Down
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pre-commit
PyYAML
aiohttp>=3.7.4,<4
aiohttp>=3.7.4,<4
APScheduler
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
# 执照
license="Tencent",
# 安装依赖
install_requires=["aiohttp>=3.7.4,<4", "PyYAML"],
install_requires=["aiohttp>=3.7.4,<4", "PyYAML", "APScheduler"],
# 分类
classifiers=[
# 发展时期,常见的如下
Expand Down