準備
- Python3
- Python Itchat庫(可以通過
pip install itchat
來安裝) - (可選)Python Pymongo庫(可以通過
pip install pymongo
來安裝) - (可選)MongoDB(請自行百度)
那現在開始吧!
引入庫
程式碼:
import re
import itchat
import pymongo
import requests
from urllib.parse import quote
其中:
import pymongo
請根據自己的情況匯入- re(正規表示式)庫用於剔除多餘的AI表情字元(如
{face:14}
這種) - itchat 庫用於發微信
- pymongo 庫用於將接收的資料儲存到資料庫
- requests 庫用於獲取AI通話的內容
- urllib.parse.quote 用於將聊天的內容轉換成URL
主函式
s = requests.Session()
msg_url = "http://api.qingyunke.com/api.php?key=free&appid=0&msg={message}"
client = pymongo.MongoClient('localhost', 27017)
db = client['wechat']
collection = db['wechat']
@itchat.msg_register(itchat.content.TEXT)
def _(msg):
print(msg)
collection.insert_one(msg)
if msg.toUserName == "filehelper":
r = s.get(msg_url.format(message=quote(msg['Text'])))
print(r.json())
msg.user.send(re.sub('\{.*?\}', '', r.json()["content"]))
itchat.auto_login(hotReload=True)
itchat.run()
其中:
- 定義client, db, collection的請根據自己的情況取捨
- 其餘程式碼請自行消化
全部程式碼
import re
import itchat
import pymongo
import requests
from urllib.parse import quote
s = requests.Session()
msg_url = "http://api.qingyunke.com/api.php?key=free&appid=0&msg={message}"
client = pymongo.MongoClient('localhost', 27017)
db = client['wechat']
collection = db['wechat']
@itchat.msg_register(itchat.content.TEXT)
def _(msg):
print(msg)
collection.insert_one(msg)
if msg.toUserName == "filehelper":
r = s.get(msg_url.format(message=quote(msg['Text'])))
print(r.json())
msg.user.send(re.sub('\{.*?\}', '', r.json()["content"]))
itchat.auto_login(hotReload=True)
itchat.run()
程式效果
資料庫裡:
(此為部分資料)