1. 程式人生 > >Python qqbot 實現qq機器人

Python qqbot 實現qq機器人

qqbot專案Gayhub地址:https://github.com/pandolia/qqbot

 

# -*- coding: utf-8 -*-
import qqbot
from qqbot import QQBotSlot as qqbotslot, RunBot
from qqbot import _bot as bot
import time
import json
import urllib


keyList = ['撿', '丟', '飯卡', ]  # 匹配關鍵字

def check(keylist, str):
    for key in keyList:
        if (key in str):
            return True
    return False

@qqbot.QQBotSlot
def onQQMessage(bot, contact, member, content):
    # bot: QQBot物件,提供List / SendTo / Stop / Restart等介面
    # contact: QContact物件,訊息的傳送者,具有ctype / qq / uin / nick / mark / card / name等屬性
    # member: QContact物件,僅當本訊息為群訊息或討論組訊息時有效,代表實際發訊息的成員
    # content: str物件,訊息內容
    if '@ME' in content:  # 如果有人艾特的機器人
        message = content.replace('[@ME]  ', '')
        # 新增名字的ASCII碼,能夠進行語義的連貫,而不是突兀的開啟另外一段對話
        asciistr = ''
        for i in range(len(member.name)):
            asciistr += (str(ord(member.name[i])))  # 組裝名字的字元編碼,儘量的是唯一的
            if i > 3:
                break
        # 呼叫圖靈機器人,進行對話的回覆,如果出現圖靈機器人,替換為浮沉沉
        bot.SendTo(contact, get_message(message, int(asciistr)).replace('圖靈機器人', '浮沉沉'))

    elif content == '-stop':
        bot.SendTo(contact, 'QQ機器人已關閉')
        bot.Stop()
    elif check(keyList, content) and member.name != '靜默':
        # bot.SendTo(contact, '您傳送的訊息是' + content)
        datatime = time.strftime('%Y.%m.%d %H:%M:%S', time.localtime(time.time()))
        print('member =', member.name + '', 'contact =', contact.name)
        strzz = contact.name + ':' + datatime + " " + member.name + "傳送訊息:" + content  # 組裝訊息
        sendMsgToGroup(strzz, ['測試資料群'], bot)
        print(strzz + " contact.mark" + contact.mark)


def sendMsgToGroup(msg, groupList, bot):
    # print('向群裡傳送訊息')
    for group in groupList:
        print('group =', group)
        bg = bot.List('group', group)
        if bg:
            b = bg[0]
            bot.SendTo(b, msg)

def sendMsgToBuddy(msg, buddyList, bot):
    # print('向好友傳送訊息')
    for buddy in buddyList:
        print('buddy', type(buddy), buddy)
        bb = bot.List('buddy', buddy)
        if bb:
            b = bb[0]
            bot.SendTo(b, msg)

def main(bot):
    groupMsg = '測試訊息是傳送到群裡面的'
    buddyMsg = '測試訊息是傳送給好友的'
    # print('os.getcwd()', os.getcwd())
    with open('./qq.txt', 'r', encoding='UTF-8') as fr:
        qqGroup = fr.readline().strip()
        qqBuddy = fr.readline().strip()
        print('fr', fr, '\nqqGroup =', qqGroup, '\nqqBuddy', qqBuddy)
    qqGroupList = qqGroup.split(',')
    qqBuddyList = qqBuddy.split(',')
    # sendMsgToGroup(groupMsg, qqGroupList, bot)
    # sendMsgToBuddy(buddyMsg, qqBuddyList, bot)


def get_message(message, userid):
    tuling = '2581f443bf364fd8a927fe87832e3d33'  # 圖靈機器人的id(使用者自己建立的)
    api_url = "http://openapi.tuling123.com/openapi/api/v2"  # API介面呼叫
    req = {
        "perception":
            {
                "inputText":
                    {
                        "text": message
                    },

                "selfInfo":
                    {
                        "location":
                            {
                                "city": "深圳",
                                "province": "廣州",
                                "street": "XXX"
                            }
                    }
            },
        "userInfo":
            {
                "apiKey": tuling,
                "userId": userid
            }
    }
    req = json.dumps(req).encode('utf8')
    http_post = urllib.request.Request(api_url, data=req, headers={'content-type': 'application/json'})
    response = urllib.request.urlopen(http_post)  # 得到網頁HTML程式碼
    response_str = response.read().decode('utf8')  # 將網頁的程式碼轉化為UTF-8 處理 避免亂碼
    response_dic = json.loads(response_str)  # 將得到的json格式的資訊轉換為Python的字典格式
    results_text = response_dic['results'][0]['values']['text']
    return results_text



if __name__=='__main__':
    bot.Login(['-q', '710469775'])
    # main(bot)

    RunBot()