python實現微信機器人

  • 首先去思知申請個賬號,創建個機器人,把appid換成你自己的;

  • 安裝相應的包,將代碼貼到python文件中,運行文件,手機微信掃碼登陸,然後就機器人就跑起來了,爲這裏沒有對文字、圖片、自帶的圖片進行處理,還是可以優化的,圖片分爲自己收集的圖片、表情和系統自帶的表情。

  • 相關資源:
    思知官網:https://www.ownthink.com/
    思知接口文檔:https://www.ownthink.com/docs/
    wxpy其他相關用法:https://www.cnblogs.com/linhaifeng/articles/9057200.html

  • 附代碼:

#! --*-- coding: utf-8 --*--

import requests
import json
from wxpy import *
import pprint

bot = Bot(console_qr=True, cache_path=True)  # 必須先登錄過一次以後纔可以使用緩存

si_zhi_url = 'https://api.ownthink.com/bot'
appid = ''

# 獲取返回消息
def auto_reply_sizhi(text):
    payload = {
    "spoken": text,
    "appid": appid,
    "userid": "user"
    }
    r = requests.post(si_zhi_url, data=json.dumps(payload))
    result = json.loads(r.content)
    message += result['data']['info']['text']
    if 'heuristic' in result['data']['info'] and result['data']['info']['heuristic']:
        for item in result['data']['info']['heuristic']:
            message += ',  ' + item

    return message

# 監聽接收到的消息
@bot.register()
def forward_message(msg):
    return auto_reply_sizhi(msg.text)

# 讓程序一直運行
embed()

如果你不想自動回覆羣消息,可以將下面這個方法重寫:

@bot.register()
def forward_message(msg):
    pprint.pprint("接收到的數據:")
    pprint.pprint(msg)
    print(msg)
    if 'Group' not in str(type(msg.sender)):
        return auto_reply_sizhi(msg.text)
    else:
        pass
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章