NoneBot总结

本文介绍了如何在NoneBot中自定义环境变量以管理全局设置,使用`on_command`实现指令交互,以及降低QQ风控的方法,包括实名认证、修改密码和定时发送消息。还涵盖了发送图片消息、随机API调用和消息响应的实战教程。
摘要由CSDN通过智能技术生成

NoneBot总结

1.自定义环境变量

呃,目前我用这个的作用就是方便管理。

比如我想设置一个全局的变量BOT_ID 表示当前机器人的qq号。

每次编写插件的时候都重写一遍qq号很不方便,考虑用一个变量代替。

.env.dev 文件下(这里看你.env 使用的是那套环境配置,如果是prod,则在prod下)

BOT_ID=1548638709 #我的机器人qq号

引入该变量的时候,就可以如下面引用。

    driver = get_driver()
    BOT_ID = str(driver.config.bot_id)
    bot = driver.bots[BOT_ID]

2.on_command

最简单的给机器人发送指定的消息,机器人回复指定的消息。

from nonebot import on_command
from nonebot.adapters.cqhttp import Bot, Event

test = on_command('hello', priority=2)


# 测试发送指定消息 机器人回复的内容 注意发送指令时要加/  /hello

@test.handle()
async def hello(bot: Bot, event: Event, state: dict):
    await bot.send(
        event=event,
        message='hello',
    )

3.发送图片消息

    message = [
        {
            "type": "text",
            "data": {
                "text": '今天是' + week_now() + '~\n'
                        + '美好的一天从刷题开始~\n'
            }
        },
        {
            "type": "image",
            "data": {
                "file": "https://img2.baidu.com/it/u=2957670248,2456554858&fm=26&fmt=auto&gp=0.jpg",
            }
        }
    ]

在这里插入图片描述

发送本地图片

基于windows

    message=[
        {
            "type": "image",
            "data": {
                "file": 'file:///D:/PyProject/spider/qqbot/src/plugins/pic1.png'
            }
        }
    ]

利用os模块获取本地图片绝对路径。

    file_path = os.path.abspath(__file__)
    dir_path =os.path.dirname(file_path)
    path = 'file:///' + dir_path + '\\resources\\menu.png'
    path = path.replace('\\', '/')

在这里插入图片描述

os.path.abspath 获取文件绝对路径。

os.path.dirname 获取文件所在目录绝对路径。

注意如果是反斜杠读取不了,只能用正斜杠。

file:///D:\PyProject\spider\qqbot\src\plugins\resources\menu.png
随机图片的接口
https://source.unsplash.com  #随机各种类型
https://api.ixiaowai.cn/ #支持json
https://api.lyiqk.cn/  #支持json 20000+图片
https://acg.yanwz.cn/ #随机动漫图片,无法返回json或跳转url,只能返回图片
https://img.paulzzh.com/ #东方project 支持302和json
https://random.52ecy.cn/ #二次元支持json & 302 有时会404
https://zhuanlan.zhihu.com/p/336053929 #知乎网站收集

使用request获取图片url

注意verify=False ,但是还是会有警告。

如果不喜欢看红色警告,可以加上这样一句话。

requests.packages.urllib3.disable_warnings()
requests.packages.urllib3.disable_warnings()
def get_mc():
    url = 'https://api.ixiaowai.cn/mcapi/mcapi.php'
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36'
    }
    res = requests.get(url, headers=headers, verify=False)
    return res.url

获取图片api实例

web_url = 'https://api.ixiaowai.cn/api/api.php?return=json'
f = Factory.create()
requests.packages.urllib3.disable_warnings()
if __name__ == '__main__':
    def fun(url):
        headers = {
            'user-agent': f.user_agent()
        }
        r = requests.get(web_url, headers=headers,verify=False)
        c = r.text
        if c.startswith(u'\ufeff'):
            c = c.encode('utf8')[3:].decode('utf8')
        j = json.loads(c)
        return j['imgurl']
    print(fun(web_url))
            # {'code': '200', 'imgurl': 'https://tva2.sinaimg.cn/large/0072Vf1pgy1foxk6m2xufj31hc0u0aru.jpg', 'width': '1920', 'height': '1080'}
有趣的随机文本api
http://oddfar.com/archives/49/

4.降低qq风控

  • qq钱包实名认证

    不知道我的手机qq实名认证的时候,获取地区失败,如果出现同样的问题,请先下载极速版qq。

  • 修改密码

5.定时任务

传送门1

传送门2

实例:全天问候。

# 获取当前是星期几
week_list = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
word_list = ['美好的一周从周一开始~\n早上好呀~~\n',
             '今天是周二~\n又是元气满满一天~~\n',
             '每天起床第一句,先给自己打个气~\n周三早上好~~\n',
             '今天是周四~\n不要忘记好好学习噢~~\n',
             '今天是周五~\n宜: 学习和刷题~~'
             '早上好~~\n周六快乐~~\n',
             '今天是周日~\n不要忘记学习和刷题噢~\n']

def week_now():
    return week_list[time.localtime().tm_wday]


def word_now():
    return word_list[time.localtime().tm_wday]


# MC酱的表情包
url_mc = 'https://api.ixiaowai.cn/mcapi/mcapi.php'
# 风景壁纸
url_scenery = 'https://api.ixiaowai.cn/gqapi/gqapi.php'
requests.packages.urllib3.disable_warnings()


def get_mc(url):
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36'
    }
    res = requests.get(url, headers=headers, verify=False)
    return res.url

# 定时消息 (全天)

@scheduler.scheduled_job('cron', day_of_week='0-6', hour=8, minute=30)
async def demo():
    driver = get_driver()
    BOT_ID = str(driver.config.bot_id)
    bot = driver.bots[BOT_ID]
    group_id = int(driver.config.group_id)
    # group_id_1 = int(driver.config.group_id_1)
    msg = word_now()
    message = [
        {
            "type": "text",
            "data": {
                "text": msg
            }
        },
        {
            "type": "image",
            "data": {
                "file": get_mc(url_mc),
            }
        }
    ]
    await bot.send_group_msg(group_id=group_id, message=message)

6.消息响应

1.群成员增加响应。

一个简单的实例。

# 群成员增加消息响应
GroupIncrease_CS = on_notice()


@GroupIncrease_CS.handle()
async def method(bot: Bot, event: GroupIncreaseNoticeEvent, state: dict):
    if event.group_id == group_id_1:
        message = [
            {
                "type": "text",
                "data": {
                    "text": "\n"
                }
            },
            {
                "type": "face",
                "data": {
                    "id": "49"
                }
            },
            {
                "type": "text",
                "data": {
                    "text": '欢迎你来到CS-21新生群~~'
                }
            },
            {
                "type": "face",
                "data": {
                    "id": "49"
                }
            },
            {
                "type": "text",
                "data": {
                    "text": '\n入群修改备注:~~\n新生: 21新生xxx\n~~非新生: 班级+姓名'
                }
            }
        ]
        await bot.send(
            event=event,
            message=message,
            at_sender=True
        )

7.linux下的 cqhttp 更新

cd qqbot # 进入到cqhttp对应的目录下
./go-cqhttp update  [可指定镜像源]
# 如: ./go-cqhttp update https://github.rc1844.workers.dev 

几个可用的镜像源

  • https://hub.fastgit.org
  • https://github.com.cnpmjs.org
  • https://github.bajins.com
  • https://github.rc1844.workers.dev
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

酷酷的Herio

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值