日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

QQ 机器人开发

發布時間:2023/12/10 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 QQ 机器人开发 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1. 利用 Python 讀取 QQ 消息

目錄

  • QQ機器人基礎知識
  • 前期配置
  • QQ機器人實現代碼
  • 本次作業
  • 1. QQ機器人基礎知識

    本教程使用 QQ 機器人的實現基于 NoneBot,而 NoneBot 有以下幾點基本信息需要你了解即可:

    • NoneBot 是一個基于 酷Q 的 Python 異步 QQ 機器人框架
    • 酷Q實現了一個“無頭QQ客戶端”(無頭就是,沒有正常操作的 Windows(窗口)所有操作通過代碼或命令行實現)
    • 所有事件(收到消息、通知等)會通過傳送給 酷Q 的HTTP API 插件
    • https://nonebot.cqp.moe/guide/(NoneBot 文檔,可以自行了解)
    • NoneBot 僅支持Python 3.6.1+
    • 僅限 Windows 系統,Mac 系統需安裝虛擬機。(個人了解到的)

    2. 前期配置

    2.1 安裝 NoneBot 使用如下命令:

    pip3 install nonebot

    運行結果:

    clela@黃家寶 C:\Users\clela\Desktop $ pip install nonebot Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple 省略中間大部分信息 Installing collected packages: toml, priority, typing-extensions, hypercorn, aiofiles, Quart, hstspreload, rfc3986, sniffio, httpx, aiocqhttp, aiocache, nonebotRunning setup.py install for hstspreload ... doneRunning setup.py install for aiocqhttp ... doneRunning setup.py install for nonebot ... done Successfully installed Quart-0.11.3 aiocache-0.11.1 aiocqhttp-1.2.3 aiofiles-0.4.0 hstspreload-2020.3.12 httpx-0.12.0 hypercorn-0.9.2 nonebot-1.4.2 priority-1.3.0 rfc3986-1.3.2 sniffio-1.1.0 toml-0.10.0 typing-extensions-3.7.4.1

    如果像上面的一樣,則安裝成功。NoneBot 安裝完了我們來安裝 酷Q 。

    2.2 安裝 酷Q

    Download_Link:https://cqp.cc/b/news

    進入頁面之后,我們能看見如下頁面:

    上面有三個版本,我們主要來看前兩個版本,一個是 酷Q Air 5.15 ~ 輕盈,夢想,新生 ~,另一個是 酷Q Pro 5.15 這里我們使用 免費 般的酷Q Air,如果你需要更多功能自行選擇 Pro 付費版本。

    我點擊 酷Q Air 之后,見到如下界面:

    下載 酷Q Air 圖靈版 或 小 i 版都可以,這里我選擇下載圖靈版本。我們下載完成之后,去安裝一下插件。

    悅創小提示:

    版本區別:

    圖靈版 = 酷Q Air + 圖靈機器人應用(官網)

    小i版 = 酷Q Air + 小i機器人應用(官網)

    2.3 安裝 coolq-http-api

    有以下幾種下載方法:

    方法一(推薦):

  • 關注公眾號:AI悅創,后臺回復 QQ 機器人
  • 把 io.github.richardchien.coolqhttpapi.cpk 放到 酷Q Air 的 App 文件夾里面
  • **注意:**如果是從我從公眾號下載的,解壓完成之后。后面幾步直接跳過,直接看第三步。
  • 方法二:

  • https://github.com/richardchien/coolq-http-api/releases
  • 下載 io.github.richardchien.coolqhttpapi.cpk
  • 放到 酷Q Air 的 app 文件夾里面
  • 悅創提示:

    注意如果 酷Q 啟動時報錯說插件加載失敗,或者系統彈窗提示缺少 DLL 文件,請 參考:https://cqhttp.cc/docs/4.12/#/

    上面 2.2 與 2.3 我們下載了所需要的 酷Q Air 圖靈版和 coolq-http-api,接下來我帶大家安裝一下:

  • 解壓我們下載的 酷Q Air 壓縮包,放到你自己的項目目錄下。
  • 將 io.github.richardchien.coolqhttpapi.cpk 放到 酷Q Air 的 app 文件夾里面
  • 最終效果圖:


    3. QQ機器人實現代碼

    首先,在我們編寫代碼之前我們先運行 CQA.exe ,接下來按它的提示操作即可。

    如果出現自動更新,讓它更新即可:


    勾選同意條款,然后點擊確認:


    點擊確認即可:


    登陸你的 QQ 號,悅創提醒你使用小號操作!


    如果,需要驗證,則自行驗證:

    登陸之后,會有一個懸浮框并且在工具欄會有圖標。


    注意:

    我們一定要在任務欄該程序圖標右鍵:應用 >>> 應用管理 >>> 啟用 HTTP API,你如果不啟用,光放插件時沒有效果的。


    全部選擇允許即可,之后你會看見如下內容:


    上面操作完了,我們就可以退出這個 酷Q 了。

    3.1 配置 HTTP API

    在 data/app/io.github.richardchien.coolqhttpapi/config/ 下可以看到一個以你登錄QQ號命名 的.json文件

    打開該文件然后找到下面三個配置項

    • ws_reverse_api_url
    • ws_reverse_event_url
    • use_ws_reverse

    修改為如下內容:

    "ws_reverse_api_url": "ws://127.0.0.1:8080/ws/api/","ws_reverse_event_url": "ws://127.0.0.1:8080/ws/event/","ws_reverse_reconnect_interval": 3000,"ws_reverse_reconnect_on_code_1000": true,"use_ws_reverse": true,

    記得保存哦!

    3.2 編寫一個主啟動程序

    保存為 main.py,先載入內置的插件測試效果:

    """ project = 'Code', file_name = 'main', author = 'AI悅創' time = '2020/3/16 0:01', product_name = PyCharm # code is far away from bugs with the god animal protectingI love animals. They taste delicious. """ import nonebotif __name__ == '__main__':nonebot.init()nonebot.load_builtin_plugins()nonebot.run(host='127.0.0.1', port=8080)

    運行該文件并啟動 酷Q 機器人,Python 程序確保已啟動。

    悅創提醒:

    先運行 酷Q 并啟動 Http API 然后再運行 Python 代碼。


    如果顯示連接成功,就表明二則應該已經連接上了。


    3.3 嘗試一下給機器人賬號發指令

    用另一個賬號給你登錄的機器人賬號發一條指令:/echo 你好,世界 機器人會給你回復一段相同的話

    /echo 你好,悅創。

    如果上面成功了,就表明你的機器人時成功的。接下來我們繼續配置一下我們的項目。

    3.4 配置我們的項目結構

    新建一個 config.py 文件,放在和 main.py 同一個位置。

    """ project = 'Code', file_name = 'config.py', author = 'AI悅創' time = '2020/3/16 0:18', product_name = PyCharm # code is far away from bugs with the god animal protectingI love animals. They taste delicious. """ from nonebot.default_config import *SUPERUSERS = {123123123}

    創建一個 MyBot 文件夾,在里面創建一個 plugins 文件夾 在里面創建一個 bot.py 文件

    ├── MyBot │└── plugins │ └── bot.py ├── main.py └── config.py
    3.4.1 修改 main.py 文件

    加載我們的插件,嘗試運行:

    """ project = 'Code', file_name = 'main', author = 'AI悅創' time = '2020/3/16 0:01', product_name = PyCharm # code is far away from bugs with the god animal protectingI love animals. They taste delicious. """ import nonebot import config from os import pathif __name__ == '__main__':nonebot.init(config) # 初始化# 加載我們自己的插件nonebot.load_plugins(path.join(path.dirname(__file__), 'MyBot', 'plugins'),'MyBot.plugins')nonebot.run(host='127.0.0.1', port=8080)

    加載我們的插件,嘗試運行:

    clela@黃家寶 C:\Code\pycharm_daima\交流群直播代碼\QQ 機器人 $ Python main.py ujson module not found, using json msgpack not installed, MsgPackSerializer unavailable [2020-03-16 00:35:49,645 nonebot] INFO: Succeeded to import "MyBot.plugins.bot" [2020-03-16 00:35:49,646 nonebot] INFO: Running on 127.0.0.1:8080 Running on http://127.0.0.1:8080 (CTRL + C to quit) [2020-03-16 00:35:49,657 nonebot] INFO: Scheduler started [2020-03-16 00:35:49,664] Running on 127.0.0.1:8080 over http (CTRL + C to quit) [2020-03-16 00:35:49,728] 127.0.0.1:58360 GET /ws/api/ 1.1 101 - 7978 [2020-03-16 00:35:49,735] 127.0.0.1:58361 GET /ws/event/ 1.1 101 - 4981 [2020-03-16 00:35:49,738] INFO in __init__: received event: meta_event.lifecycle.connect [2020-03-16 00:36:02,679] ASGI Framework Lifespan error, shutdown without Lifespan support

    從上面可以看見:Succeeded to import "MyBot.plugins.bot" 表示我們的插件成功導入,頁正常運行。

    3.4.2 修改 bot.py

    找到我們在 plugins 文件夾中的 bot.py 文件,加入以下內容 :

    """ project = 'Code', file_name = 'bot.py', author = 'AI悅創' time = '2020/3/16 0:30', product_name = PyCharm # code is far away from bugs with the god animal protectingI love animals. They taste delicious. """ import nonebotbot = nonebot.get_bot()@bot.on_message('private') async def _(ctx):print(ctx)

    當你修改完你的程序,你可以使用 QQ 私聊消息,你將會在控制臺看到有內容輸出:

    {'font': 6889288, 'message': [{'type': 'text', 'data': {'text': '你好,我是悅創'}}], 'message_id': 28, 'message_type': 'private', 'post_type':'message', 'raw_message': '你好,我是悅創', 'self_id': 1423120581, 'sen der': {'age': 1, 'nickname': 'AI悅創', 'sex': 'male', 'user_id': 1432803776}, 'sub_type': 'friend', 'time': 1584317165, 'user_id': 1432803669}

    我們可以看到這幾點:

    • raw_message:消息內容
    • user_id:給你發私聊 消息的 QQ 號

    那這時候有同學會問了,那群聊消息該如何處理呢?改成 group 就是群聊消息處理:

    import nonebotbot = nonebot.get_bot()@bot.on_message('group') # 如果收到一條群聊的信息時,進入函數里面處理。 async def _(ctx):print(ctx)

    群聊消息將會看到有內容輸出:

    {'anonymous': None, 'font': 6889000, 'group_id': 813167307, 'message': [{'type': 'text', 'data': {'text': '測試用例'}}], 'message_id': 32, 'message_ type': 'group', 'post_type': 'message', 'raw_message': '測試用例', 'self_id': 1432803990, 'sender': {'age': 1, 'area': '法國', 'card': '', 'level': '潛水', 'nickname': 'AI悅創', 'role': 'owner', 'sex': 'male', 'title': '', 'user_id': 1432803990}, 'sub_type': 'normal', 'time': 1584318928, 'user_id': 1432803990}
    • group_id:群聊號
    • user_id:發消息的 QQ 號
    • raw_message:具體的消息內容

    當然,如果你不想創建群,你可以加入我的 QQ 群進行測試,QQ 群號:813167307,不知道同學有沒有發現,我們得到的結果其實就相當于一個 Python 中的數據類型 字典(dictionary)可以直接用的。

    3.5 處理加群消息

    """ project = 'Code', file_name = 'bot.py', author = 'AI悅創' time = '2020/3/16 0:30', product_name = PyCharm # code is far away from bugs with the god animal protectingI love animals. They taste delicious. """ from nonebot import on_request, RequestSession# 將函數注冊為群請求處理器 @on_request('group') async def _(session: RequestSession):# 判斷驗證信息是否符合要求if session.ctx['comment'] == 'aiyc':# 驗證信息正確,同意入群await session.approve()return# 驗證信息錯誤,拒絕入群await session.reject('請說暗號')
    3.5.1 接收新人入群消息
    from nonebot import on_notice, NoticeSession # 將函數注冊為:群成員增加通知處理器 @on_notice('group_increase') async def _(session: NoticeSession):print('有新人來了')

    4. 本次作業

    編寫一個Python程序,要求

  • 讀取QQ消息

  • 將聊天內容儲存到Excel表格中

  • 根據不同人/群聊來創建不同的sheet,一個sheet對應一個人/群聊


  • 2. 利用 Python 發送 QQ 消息

    目錄

  • 發送消息
  • 本次作業
  • 1. 發送消息

    1.1 發送私聊消息

    bot.send_private_msg(user_id=對方QQ, message=具體消息)

    @bot.on_message('private') # 如果收到一條私聊的信息時,進入函數里面處理。 # 實現在我們收到一條私聊消息的時候,它到底有哪些內容在里面呢? async def _(ctx):msg = ctx['raw_message']user_id = ctx['user_id']# bot.send_private_msg(user_id=對方的 QQ, message=對方具體的消息) 你在別的地方也是可以使用的await bot.send_private_msg(user_id = user_id, message = msg)print(ctx)

    1.2 發送群聊消息

    bot.send_group_msg(group_id=群號, message=具體消息)

    @bot.on_message('group') # 如果收到一條群聊的信息時,進入函數里面處理。 async def _(ctx):user_id = ctx['user_id']# if user_id == 指定 QQ 號:if user_id == ctx['user_id']:group_id = ctx['group_id']await bot.send_group_msg(group_id = group_id, message = "說的對")

    1.3 歡迎新成員

    對于有session的,可以直接session.send()

    @on_notice('group_increase') # 帶類型的參數 async def _(session: NoticeSession):await session.send("歡迎新朋友~")

    1.4 發布群公告

    bot._send_group_notice(group_id=群號, title=群公告標題, content=群公告內容)

    注意_send_group_notice最開頭有一個下劃線

    1.5 群組設置某人禁言

    bot.set_group_ban(group_id=群號, user_id=QQ號, duration=秒為單位的禁言時間)

    @bot.on_message('group') # 如果收到一條群聊的信息時,進入函數里面處理。 async def _(ctx):user_id = ctx['user_id']# if user_id == 指定 QQ 號:if user_id == ctx['user_id']:group_id = ctx['group_id']await bot.send_group_msg(group_id = group_id, message = "說的對")msg = ctx['raw_message']if '傻瓜' == msg:group_id = ctx['group_id']user_id = ctx['user_id']await bot.send_group_msg(group_id=group_id, message=f"{msg}你不良言行,已經被禁言!")await bot.set_group_ban(group_id = group_id, user_id = user_id, duration = 15*60)

    1.6 群組踢人

    bot.set_group_kick(group_id=群號, user_id=要踢的人QQ號, reject_add_request=是否不允許再加群)

    @bot.on_message('group') # 如果收到一條群聊的信息時,進入函數里面處理。 async def _(ctx):user_id = ctx['user_id']msg = ctx['raw_message']# if user_id == 指定 QQ 號:group_id = ctx['group_id']if user_id == ctx['user_id']:await bot.send_group_msg(group_id = group_id, message = "說的對")if msg == '傻瓜':await bot.send_group_msg(group_id=group_id, message=f"{msg}你不良言行,已經被禁言!")await bot.set_group_ban(group_id = group_id, user_id = user_id, duration = 15*60)if msg == '退群':await bot.set_group_kick(group_id = group_id, user_id = user_id, reject_add_request = True)

    2. 本次作業

    定時群發公告機器人,編寫一個Python程序,要求

  • 程序啟動后從 group_notice.json 文件中讀取要群發的群號及群公告 內容

  • 按照指定時間定時發送(比如每周一三五下午三點)

  • 悅創提示:如需要完整代碼,關注公眾號:AI悅創,后臺回復: QQ機器人

    總結

    以上是生活随笔為你收集整理的QQ 机器人开发的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。