Search code examples
pythonglobal-variablesapi-design

Python teamspeak3 api


I'm creating a bot for TS3 with API from github.

In main.py I create connection instance named ts3conn using TS3Connection class. Then I register an event like this: `ts3conn.register_for_channel_events(channel_id, event_handler)

In module.py I create an event_handler like this:

event_handler(sender, **kw):
    event = kw["event"] # variable 'event' contains target_channel_id (to which client moved) and client_id 
    # Here I need to use the ts3conn instance from main, don't know how.

So I tried by doing from main import ts3conn in module.py but it halts. I tried to understand the TS3Connection.py and Events.py (the most important files) but the author uses module "blinker" and I have no idea how can I edit those files.

If you are able to help me, I can happily accept primitive methods of solving the problem but also I want to stay with current structure of main, containing connection and modules directory containing functions that use the connection to communicate with the TS3 server.


Solution

  • Wrap the handling_event function with a class that will pass the ts3conn to the handler when is called.

    class event_handler(object):
        def __init__(self, ts3conn):
            self.ts3conn = ts3conn
    
        def handle_event(self, sender, **kw):
            print(self.ts3conn)
            # some operations on ts3conn
    
    # in main
    handler = event_handler(ts3conn)
    ts3conn.register_for_channel_events(1, handler.handle_event)