V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2020-04-21 20:57:42 +08:00 · 2063 次点击
    这是一个创建于 1473 天前的主题,其中的信息可能已经有所发展或是发生改变。

    想用 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
       2020-04-22 09:00:43 +08:00
    救命啊= =
    bnm965321
        2
    bnm965321  
       2020-04-22 11:06:50 +08:00
    没看懂你在说啥,你在哪里调用 get_cookies(),为什么不能获取它的返回值?
    black201w
        3
    black201w  
    OP
       2020-04-22 12:21:37 +08:00
    @bnm965321 比如说我就在 main 里调用 bot.get_cookies(),服务器返回给我 json 是给 on_message()处理了,但我想让它成为 get_cookies()的返回值
    bnm965321
        4
    bnm965321  
       2020-04-22 12:28:56 +08:00
    你要把服务器给你的 cookies json 先缓存,websocket 是推送模型。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2226 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 02:39 · PVG 10:39 · LAX 19:39 · JFK 22:39
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.