推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
black201w
V2EX  ›  Python

关于 Python 中 websocket-client 库的使用有一些疑惑

  •  
  •   black201w · Apr 21, 2020 · 2541 views
    This topic created in 2240 days ago, the information mentioned may be changed or developed.

    想用 websocket-client 库和这个项目 https://github.com/Chocolatl/qqlight-websocket 写一个 QQ 机器人,我的 python 代码大致如下

    import time
    import websocket
    import json
    
    
    class QLWebSocket:
        def __init__(self, address="127.0.0.1", port=2333, path="/"):
            def on_open(*args):
                def run(*args):
             
                    # 发送这段 json,服务器返回现在登录的 QQ 号,返回的 json 如下
                    # {"id": "1.048596", "result": "114514"}
                    # id 与发送的 id 相同,result 为 QQ 号
                    
                    self.ws.send('{"id": "1.048596","method": "getLoginAccount"}')
                    
                thread.start_new_thread(run, ())
                
            ws_link = "ws://%s:%d%s" % (address, port, path)
            self.ws = websocket.WebSocketApp(ws_link,
                                             on_message=self.on_message,
                                             on_close=self.on_close)
            self.ws.on_open = on_open
            
            
        def on_message(self, message): # message 为服务器发送的 json 字符串
        	print(message)
            
        def get_cookies(self):
        	self.ws.send('{"id": "1.16584161","method": "getCookies"}')
            
            
    bot = QLWebSocket()
    
    
    if __name__ == '__main__':
        bot.run()
    

    现在的问题就是,只要是服务器发送过来的 json 都会由 on_message()函数处理。

    我想要的效果是比如在我执行 get_cookies()函数时,能直接通过 get_cookies()返回获取到的 cookie 字符串

    所以请问各位大佬应该怎么实现这个效果呢?

    black201w
        1
    black201w  
    OP
       Apr 22, 2020
    救命啊= =
    bnm965321
        2
    bnm965321  
       Apr 22, 2020
    没看懂你在说啥,你在哪里调用 get_cookies(),为什么不能获取它的返回值?
    black201w
        3
    black201w  
    OP
       Apr 22, 2020
    @bnm965321 比如说我就在 main 里调用 bot.get_cookies(),服务器返回给我 json 是给 on_message()处理了,但我想让它成为 get_cookies()的返回值
    bnm965321
        4
    bnm965321  
       Apr 22, 2020
    你要把服务器给你的 cookies json 先缓存,websocket 是推送模型。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4178 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 45ms · UTC 05:22 · PVG 13:22 · LAX 22:22 · JFK 01:22
    ♥ Do have faith in what you're doing.