miguelgrinberg / python-socketio

Python Socket.IO server and client
MIT License
4k stars 586 forks source link

SocketIO Client function not running event is called. #695

Closed TechStudent10 closed 3 years ago

TechStudent10 commented 3 years ago

I created a previous issue, so you probably know what is happening. I have created a chat app using Flask SocketIO and am now trying to create a bot API for it. For some reason, the function that should be called when a message is being received isn't running. I can obviously send a message from the chat app UI and from the Bot. But it won't even detect that.

My Bot Code:

import socketio

class Bot(object):
    _CHAT_URL = "<socketio server>"
    room_code = None

    def __init__(self, bot_username="Bot"):
        self.bot_username = bot_username

        self.sio = socketio.Client(logger=True, engineio_logger=True)

        @self.sio.event
        def message(json):
            self._on_message(json)

        self.sio.connect(self._CHAT_URL)

        self.on_init()

    def _on_message(self, **kwargs):
        if not self.room_code:
            raise Exception("Room Code Variable (room_code) not found.")

        self.on_message(**kwargs)

    def on_message(self, json):
        pass

    def send_message(self, message_json):
        self.sio.emit('message', {
            'username': self.bot_username,
            'room_code': self.room_code,
            **message_json
        })

    def run(self):
        self.sio.wait()

    def on_init(self):
        pass

My Bot Client Code:

# 'pycord' is the name of the chat app and module where the bot is. You cannot install this. This is on my local machine.
import pycord

class MyBot(pycord.Bot):
    room_code = "1"

    def on_init(self):
       self.send_message({
           'message': "Hey!"
       })

    def on_message(self, json):
        print(json)

MyBot().run()
miguelgrinberg commented 3 years ago

Have you used the examples I pointed you at in the other issue? Those are intended to help developers learn how to use this package. The documentation also includes a troubleshooting section. Sorry, but I can't really debug this code for you, it's not even something I can run.

TechStudent10 commented 3 years ago

@miguelgrinberg yes I have looked at it. I have used the troubleshooting section as you said. Nothing unusual pops up. It's fine. I'll try to fix it myself. Thanks for your time!