使用Python制作IOTQQ插件

使用Python制作IOTQQ插件

IOTQQ


IOTQQ支持WebSocket 所以我们可以通过任意支持WebSocket的编程语言来开发插件,后面我们用Python来演示开发插件的过程

开发插件

环境配置

  1. Python环境搭建 (略)
  2. 安装Socket.io
    pip install python-socketio
    pip install websocket-client

    务必安装websocket-client,否则无法使用!

开始编写插件

  1. 连接WebSocket接口:
    #coding=utf-8
    import socketio
    @sio.event
    def connect():
    print('成功连接服务器')
    sio.emit('GetWebConn',123456)#取得当前已经登录的QQ链接
    def main():
    try:
        sio.connect("http://127.0.0.1:8888",transports=['websocket'])
        sio.wait() #阻塞进程
    except BaseException as e:
        print (e)
    if __name__ == '__main__':
    main()

    查看你是否连接成功

  2. 编写相关事件:
    #coding=utf-8
    import socketio
    @sio.event
    def connect():
    print('成功连接服务器')
    sio.emit('GetWebConn',123456)#取得当前已经登录的QQ链接
    @sio.on('OnGroupMsgs')
    def OnGroupMsgs(message):
    ''' 监听群组消息'''
    print(message)
    @sio.on('OnFriendMsgs')
    def OnFriendMsgs(message):
    ''' 监听好友消息 '''
    print(message)
    @sio.on('OnEvents')
    def OnEvents(message):
    ''' 监听相关事件'''
    print(message)
    def main():
    try:
        sio.connect("http://127.0.0.1:8888",transports=['websocket'])
        sio.wait() #阻塞进程
    except BaseException as e:
        print (e)
    if __name__ == '__main__':
    main()
  3. 使用类库来信息处理
    #coding=utf-8
    import socketio
    class GMess:
    #QQ群消息类型
    def __init__(self,message1):
        #print(message1)
        self.FromQQG = message1['FromGroupId'] #来源QQ群
        self.QQGName = message1['FromGroupName'] #来源QQ群昵称
        self.FromQQ = message1['FromUserId'] #来源QQ
        self.FromQQName = message1['FromNickName'] #来源QQ名称
        self.Content = message1['Content'] #消息内容
    class Mess:
    #私聊消息类型
    def __init__(self,message1):
        self.FromQQ = message1['ToUin']
        self.ToQQ = message1['FromUin']
        self.Content = message1['Content']
    @sio.event
    def connect():
    print('成功连接服务器')
    sio.emit('GetWebConn',123456)#取得当前已经登录的QQ链接
    @sio.on('OnGroupMsgs')
    def OnGroupMsgs(message):
    ''' 监听群组消息'''
    print(message)
    @sio.on('OnFriendMsgs')
    def OnFriendMsgs(message):
    ''' 监听好友消息 '''
    print(message)
    @sio.on('OnEvents')
    def OnEvents(message):
    ''' 监听相关事件'''
    print(message)
    def main():
    try:
        sio.connect("http://127.0.0.1:8888",transports=['websocket'])
        sio.wait() #阻塞进程
    except BaseException as e:
        print (e)
    if __name__ == '__main__':
    main()

    然后你就可以开发你自己想要的功能了
    下面贴上我写的开发例程:

    #coding=utf-8
    import socketio
    import json
    import requests
    import pdb
    import re
    import logging
    import time
    import socket
    '''
    Python插件SDK Ver 0.0.2
    维护者:enjoy(2435932516)
    有问题联系我。
    '''
    robotqq = "123" #机器人QQ号
    webapi = "http://127.0.0.1:8888" #Webapi接口 http://127.0.0.1:8888
    sio = socketio.Client()
    #log文件处理
    logging.basicConfig(format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s',level=0,filename='new.log',filemode='a')
    class GMess:
    #QQ群消息类型
    def __init__(self,message1):
        #print(message1)
        self.FromQQG = message1['FromGroupId'] #来源QQ群
        self.QQGName = message1['FromGroupName'] #来源QQ群昵称
        self.FromQQ = message1['FromUserId'] #来源QQ
        self.FromQQName = message1['FromNickName'] #来源QQ名称
        self.Content = message1['Content'] #消息内容
    def send(ToQQ,Content,sendToType,atuser=0,sendMsgType='TextMsg',groupid=0):
    tmp={}
    tmp['sendToType'] = sendToType
    tmp['toUser']= ToQQ
    tmp['sendMsgType']=sendMsgType
    tmp['content']=Content
    tmp['groupid']=0
    tmp['atUser']=atuser
    tmp1 = json.dumps(tmp)
    requests.post(webapi+'/v1/LuaApiCaller?funcname=SendMsg&qq='+robotqq,data=tmp1)
    def zan(QQ)
    #QQ名片赞
    tmp={}
    tmp['UserID']=QQ
    tmp1 = json.dumps(tmp)
    requests.post(webapi+'/v1/LuaApiCaller?funcname=QQZan&timeout=10&qq='+robotqq,data=tmp1)
    def sendPic(ToQQ,Content,sendToType,imageUrl):
    #发送图片信息
    tmp={}
    tmp['sendToType'] = sendToType
    tmp['toUser']= ToQQ
    tmp['sendMsgType']="PicMsg"
    tmp['content']=Content
    tmp['picBase64Buf']=''
    tmp['fileMd5']=''
    tmp['picUrl']=imageUrl
    tmp1 = json.dumps(tmp)
    #print(tmp1)
    print(requests.post(webapi+'/v1/LuaApiCaller?funcname=SendMsg&timeout=10&qq='+robotqq,data=tmp1).text)
    class Mess:
    def __init__(self,message1):
        self.FromQQ = message1['ToUin']
        self.ToQQ = message1['FromUin']
        self.Content = message1['Content']
    # standard Python
    # SocketIO Client
    #sio = socketio.AsyncClient(logger=True, engineio_logger=True)
    # ----------------------------------------------------- 
    # Socketio
    # ----------------------------------------------------- 
    def beat():
    while(1):
        sio.emit('GetWebConn',robotqq)
        time.sleep(60)
    @sio.event
    def connect():
    print('connected to server')
    sio.emit('GetWebConn',robotqq)#取得当前已经登录的QQ链接
    beat() #心跳包,保持对服务器的连接
    @sio.on('OnGroupMsgs')
    def OnGroupMsgs(message):
    ''' 监听群组消息'''
    tmp1 = message
    tmp2 = tmp1['CurrentPacket']
    tmp3 = tmp2['Data']
    a = GMess(tmp3)
    cm = a.Content.split(' ',3) #分割命令
    '''
    a.FrQQ 消息来源
    a.QQGName 来源QQ群昵称
    a.FromQQG 来源QQ群
    a.FromNickName 来源QQ昵称
    a.Content 消息内容
    '''
    if a.Content=='#菜单':
        #print(a.ToQQ)
        send(a.FromQQG,"功能",2,a.FromQQ)
        return
    te = re.search(r'\#(.*)',str(a.Content))
    if te == None:
        return
    temp = eval(requests.get("https://hlqsc.cn/lexicon/?id="+str(a.FromQQ)+"&msg="+te.group(1)+"&name=tuling").text)
    sendtext = re.sub(r"http.*", "", temp['text'], count=0, flags=0)
    send(a.FromQQG,sendtext,2,a.FromQQ)
    '''
    图灵接口 已丢弃
    如果你有图灵api可以直接使用
    data_temp = {}
    chat_temp = {}
    user = {}
    user['apiKey'] = '587f10e38dac47bd9abbaa7cfcf3dc64'
    user['userId'] = str(a.FromQQ)
    te = re.search(r'\#(.*)',str(a.Content))
    if te == None:
        return
    chat_temp['inputText'] = {'text':te.group(1)}
    data_temp['perception'] = chat_temp
    data_temp['userInfo'] = user
    json_temp = json.dumps(data_temp)
    print(json_temp)
    temp =eval(requests.post('http://openapi.tuling123.com/openapi/api/v2',data=json_temp).text)
    temp1 = temp['results']
    text = ''
    for i in temp1:
        if i['resultType'] == 'text':
            text+= i['values']['text']
    send(a.FromQQG,text,2,a.FromQQ)
    '''
    logging.info("["+str(a.FromQQG)+']'+str(a.FromQQ)+": "+str(a.Content))
    #print(message)
    @sio.on('OnFriendMsgs')
    def OnFriendMsgs(message):
    ''' 监听好友消息 '''
    tmp1 = message
    tmp2 = tmp1['CurrentPacket']
    tmp3 = tmp2['Data']
    a = Mess(tmp3)
    #print(tmp3)
    cm = a.Content.split(' ')
    if a.Content=='#菜单':
        send(a.ToQQ,"你好",1)
    @sio.on('OnEvents')
    def OnEvents(message):
    ''' 监听相关事件'''
    print(message)   
    # ----------------------------------------------------- 
    def main():
    try:
        sio.connect(webapi,transports=['websocket'])
        #pdb.set_trace() 这是断点
        sio.wait()
    except BaseException as e:
        logging.info(e)
        print (e)
    if __name__ == '__main__':
    main()

    https://github.com/mcoo/iotqq-plugins-demo/blob/master/Python/iotqq.py

https://raw.githubusercontent.com/mcoo/iotqq-plugins-demo/master/Python/iotqq.py

欢迎star

评论

  1. 头像
    阿布| CharlieYu
    Windows Edge 81.0.416.68

    沙发

    3月前
    2020-5-03 20:37:43
    • enjoy
      enjoy 博主
      Windows Chrome 83.0.4103.61

      嘻嘻

      3月前
      2020-5-27 17:06:19
  2. 头像
    1695949332
    Windows Chrome 81.0.4044.138

    请教一下,怎么控制会话呢,比如说bot提示后要获得它人第二次发的消息

    3月前
    2020-5-24 14:30:52
    • enjoy
      enjoy 博主
      Windows Chrome 83.0.4103.61

      插件会自动阻塞主线程,它的子线程会自动处理消息,你只需要设计回复的内容就行

      3月前
      2020-5-27 16:55:29
  3. 头像
    小范
    Windows Edge 18.18363

    博主的页面真好看👀

    2月前
    2020-6-02 13:12:22
    • enjoy
      enjoy 博主
      Windows Chrome 83.0.4103.61

      嘻嘻 网站模板 在页面底下有的!

      2月前
      2020-6-03 10:04:41
  4. 头像
    kaoli
    Windows Chrome 83.0.4103.61

    xixics

    2月前
    2020-6-03 11:14:54
    • enjoy
      enjoy 博主
      Windows Chrome 83.0.4103.61

      emmm

      2月前
      2020-6-03 11:15:28
  5. 柯北
    Linux Firefox 78.0

    Name sio is not defind 难搞哦

    1月前
    2020-7-01 22:25:44
    • enjoy
      enjoy 博主
      Windows Chrome 83.0.4103.116

      注意是否安装依赖:

      pip install python-socketio
      pip install websocket-client

      还有是否引用!

      1月前
      2020-7-04 20:26:43
      • 头像
        RamuneSoda
        Windows Chrome 83.0.4103.116

        这里是前几个代码框里的bug啦,前几个代码框都需要先

        sio = socketio.Client()
        已编辑
        4周前
        2020-7-14 19:17:43
        • enjoy
          enjoy 博主
          Windows Chrome 83.0.4103.116

          博客的内容没有更新及时,请前往Github查看。有bug请提issue

          4周前
          2020-7-15 12:13:35
  6. 头像
    小费
    Windows Chrome 79.0.3945.130

    开始入坑python

    1月前
    2020-7-12 12:23:10
    • enjoy
      enjoy 博主
      Windows Chrome 83.0.4103.116

      666666

      4周前
      2020-7-15 12:13:59
  7. 头像
    沙盒梦想
    Windows Chrome 80.0.3987.132

    为啥每次尝试发送的时候都发不出去。在linux后台显示

    
    2020/08/05 19:00:23.123 [E]  QQLuaHttpVmRun /iotbot/iotbot_3.0.6_linux_amd64/WebPlugins/Api_LuaCaller.lua:18: attempt to index a non-table object(nil) with key 'toUser'
    stack traceback:
        /iotbot/iotbot_3.0.6_linux_amd64/WebPlugins/Api_LuaCaller.lua:18: in function 'fSwitch'
        /iotbot/iotbot_3.0.6_linux_amd64/WebPlugins/Api_LuaCaller.lua:180: in main chunk
        [G]: ?
    
    1周前
    2020-8-05 19:02:47
    • enjoy
      enjoy 博主
      Android Chrome 71.0.3578.141

      你调用发送的是哪个函数,可以的话把相关代码发一下

      1周前
      2020-8-05 19:32:11
      • 头像
        沙盒梦想
        Windows Chrome 80.0.3987.132

        调用的send的函数,就是

        send(a.FromQQG,"功能",2,a.FromQQ)

        这个,调用的时候会弹提示

        1周前
        2020-8-06 17:23:11
        • enjoy
          enjoy 博主
          Android Chrome 71.0.3578.141

          你看看 a.FromQQG 是不是空值

          1周前
          2020-8-06 18:02:30
  8. panghu
    Macintosh Edge 84.0.522.50

    运行成功后显示啥呢

    6天前
    2020-8-07 12:26:15
    • enjoy
      enjoy 博主
      Windows Chrome 84.0.4147.105

      你插件连接成功后发送信息会产生log

      6天前
      2020-8-07 16:07:19
  9. 头像
    阿辉
    Windows Chrome 84.0.4147.89

    写个什么机器人好呢,纠结ing…

    6天前
    2020-8-07 17:10:57
  10. allenraotao
    Windows Chrome 83.0.4103.97

    为什么我监听事件没反应了

    3天前
    2020-8-10 11:12:27
    • enjoy
      enjoy 博主
      Windows Chrome 84.0.4147.105

      博客的内容更新不及时,有些事件的名字有误,请看GitHub仓库!

      3天前
      2020-8-10 11:23:27

发送评论 编辑评论


				
上一篇
下一篇