예제 #1
0
    def __init__(self, linkinfo, parent=None):
        self.li = linkinfo
        super(QDialog, self).__init__(parent)
        setupUi(
            self,
            os.path.join(ts3.getPluginPath(), "pyTSon", "scripts", "linkinfo",
                         "linkinfo.ui"))
        self.setWindowTitle("Linkinfo by Luemmel")
        self.btn_add_domain.clicked.connect(self.add_domain)
        self.btn_remove_domain.clicked.connect(self.remove_domain)
        self.btn_add_protocol.clicked.connect(self.add_protocol)
        self.btn_remove_protocol.clicked.connect(self.remove_protocol)
        self.cb_status.stateChanged.connect(self.toggle_status)
        self.cb_mode.stateChanged.connect(self.toggle_mode)

        self.pixmap = QPixmap(
            os.path.join(ts3.getPluginPath(), "pyTSon", "scripts", "linkinfo",
                         "luemmel.png"))
        self.pixmap.scaledToWidth(110)
        self.label_image.setPixmap(self.pixmap)

        self.cb_status.setChecked(linkinfo.status)
        self.cb_mode.setChecked(linkinfo.mode)
        self.list_domain.addItems(linkinfo.domains)
        self.list_protocol.addItems(linkinfo.protocols)
예제 #2
0
    def __init__(self, ac, parent=None):

        self.ac = ac

        super(QDialog, self).__init__(parent)
        self.setWindowIcon(
            QIcon(
                os.path.join(getPluginPath(), "pyTSon", "scripts",
                             "avatarcollector", "icon.png")))
        setupUi(
            self,
            os.path.join(getPluginPath(), "pyTSon", "scripts",
                         "avatarcollector", "main.ui"))
        self.setWindowTitle("Avatar Collector")

        # Load version from plguin vars
        self.ui_label_version.setText("v" + ac.version)

        # Delete QDialog on Close
        self.setAttribute(Qt.WA_DeleteOnClose)

        # Disable help button
        self.setWindowFlags(self.windowFlags()
                            & ~Qt.WindowContextHelpButtonHint)

        self.scrollAreaWidgetContents = QWidget()
        self.gridLayout = QGridLayout(self.scrollAreaWidgetContents)
        self.ui_scroll_avatars.setWidget(self.scrollAreaWidgetContents)

        # Reload Button connect
        self.ui_btn_reload.clicked.connect(ac.loadAvatars)
예제 #3
0
 def __init__(self, parent):
     super(QDialog, self).__init__(parent)
     setupUi(self, os.path.join(getPluginPath(), "pyTSon", "scripts", "contactmanager", "info.ui"))
     self.setWindowIcon(QIcon(os.path.join(getPluginPath(), "pyTSon", "scripts", "contactmanager", "icon.png")))
     self.setWindowTitle("That was easy!")
     
     # Button connect
     self.ui_btn_ok.clicked.connect(self.closeMessageDialog)
     
     # Disable help button
     self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint | Qt.WindowStaysOnTopHint)
     
     # Delete QDialog on Close
     self.setAttribute(Qt.WA_DeleteOnClose)
예제 #4
0
def getAddonStatus(
    filename_without_extension="",
    name=""
):  # getAddonStatus("TS3Hook", "TS3Hook") getAddonStatus("tspatch", "TS Patch")
    """
    :param filename_without_extension:
    :param name:
    :return: AddonStatus
    """
    to_remove = ('_win64', '_win32', '_x64', '_x86')
    r = compile(r'({})\.dll$'.format('|'.join(map(escape, to_remove))),
                flags=IGNORECASE)
    if filename_without_extension:
        p = Process(os.getpid())
        filename = filename_without_extension.lower()
        # pattern = compile("^(?:.*)(_win64|_win32|_x64|_x86)?\.dll$", IGNORECASE|MULTILINE)
        for dll in p.memory_maps():
            # file = dll.path.lower().rsplit('\\', 1)[1].replace("_win64","").replace("_win32","").replace("_x86","").replace("_x64","").replace(".DLL","").replace(".dll","")
            file = dll.path.lower()
            if not file.endswith(".dll") and not file.endswith(".so"): continue
            file = r.sub(r'', dll.path).lower().rstrip('.dll')
            if file.endswith(filename):
                return AddonStatus.LOADED  #, ExtendedAddonStatus.MEMORY # pattern.sub("", file)
    if name:
        addons = getAddons()
        for k in addons:
            if addons[k]["name"] == name:
                return AddonStatus.INSTALLED  #, ExtendedAddonStatus.DATABASE
    if filename_without_extension:
        for filename in os.listdir(ts3lib.getPluginPath()):
            filename = r.sub(r'', filename).lower().rstrip('.dll')
            if filename == filename_without_extension:
                return AddonStatus.INSTALLED  #, ExtendedAddonStatus.FOLDER
    return AddonStatus.UNKNOWN  #, ExtendedAddonStatus.UNKNOWN
예제 #5
0
 def __init__(self, plugin, parent=None):
     super(QDialog, self).__init__(parent)
     setupUi(
         self,
         path.join(ts3lib.getPluginPath(), "pyTSon", "scripts",
                   "nowPlaying", "settings.ui"))
     self.setWindowTitle("Now Playing Settings")
예제 #6
0
 def __init__(self,serverBrowser, parent=None):
     self.serverBrowser=serverBrowser
     super(QDialog, self).__init__(parent)
     self.setAttribute(Qt.WA_DeleteOnClose)
     setupUi(self, os.path.join(ts3.getPluginPath(), "pyTSon", "scripts", "serverBrowser", "ui", "servers.ui"))
     self.setWindowTitle("PlanetTeamspeak Server Browser")
     #ts3.printMessageToCurrentTab("Countries: "+str(self.countries))
     #try:
         #self.serverList.doubleClicked.connect(self.table_doubleclicked)
         #self.serverList.connect("doubleClicked()", self.table_doubleclicked)
         #self.apply.connect("clicked()", self.on_apply_clicked)
         #self.reload.connect("clicked()", self.on_reload_clicked)
     #except:
         #ts3.logMessage(traceback.format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "PyTSon", 0)
     #self.ReasonList.connect("currentItemChanged(QListWidgetItem*, QListWidgetItem*)", self.onReasonListCurrentItemChanged)
     #self.ReasonList.connect("itemChanged(QListWidgetItem*)", self.onReasonListItemChanged)
     self.serverList.horizontalHeader().setStretchLastSection(True)
     self.serverList.setColumnWidth(0, 350)
     self.serverNameModifier.addItems(self.NAME_MODIFIERS)
     self.serverNameModifier.setEnabled(False)
     #self.pageLabel.mousePressEvent = self.on_pageLabel_clicked
     #self.cfg.set("general", "differentApi", "True" if state == Qt.Checked else "False")
     self.listCountries(True)
     #ReportDialog.ReasonList.clear()
     self.setupFilters()
     # self.serverList.doubleClicked.connect(self.doubleClicked_table)
     #ts3.printMessageToCurrentTab(str(serverBrowser.filters))
     #if serverBrowser.filters.filterServerName != "":
         #self.filterServerName.setText(serverBrowser.filters.filterServerName)
     #item.setFlags(item.flags() &~ Qt.ItemIsEditable)
     # self.countryBox.clear()
     #for item in countries:
         #self.countryBox.addItem(str(item[1]))
     #self.serverList.setStretchLastSection(true)
     self.listServers()
예제 #7
0
 def __init__(self):
     self.ini = "%s/shittyExploits/config.ini" % ts3lib.getPluginPath()
     self.cfg = loadCfg(self.ini)
     if PluginHost.cfg.getboolean("general", "verbose"):
         ts3lib.printMessageToCurrentTab(
             "{0}[color=orange]{1}[/color] Plugin for pyTSon by [url=https://github.com/{2}]{2}[/url] loaded."
             .format(timestamp(), self.name, self.author))
예제 #8
0
 def __init__(self, info, type, target, parent=None):
     super(QDialog, self).__init__(parent)
     setupUi(
         self,
         os.path.join(ts3.getPluginPath(), "pyTSon", "scripts", "info",
                      "variables.ui"))
     self.setAttribute(Qt.WA_DeleteOnClose)
     self.setupTable(type, target)
예제 #9
0
 def __init__(self, cfg, parent=None):
     self.cfg = cfg
     super(QDialog, self).__init__(parent)
     setupUi(
         self,
         os.path.join(ts3.getPluginPath(), "pyTSon", "scripts", "profile",
                      "ui", "profile.ui"))
     self.setWindowTitle("Set up profile")
예제 #10
0
파일: pytson.py 프로젝트: pathmann/pyTSon
def getPluginPath(*args):
    """
    Returns pyTSon's pluginpath, that is, the subdirectory 'pyTSon' in the
    TeamSpeak 3 plugins directory.
    @param args: path fields joined to the result as list of strings
    @type args: list[str]
    @return: The accumulated path
    @rtype: str
    """
    return os.path.join(ts3lib.getPluginPath(), "pyTSon", *args)
예제 #11
0
def getPluginPath(*args):
    """
    Returns pyTSon's pluginpath, that is, the subdirectory 'pyTSon' in the
    TeamSpeak 3 plugins directory.
    @param args: path fields joined to the result as list of strings
    @type args: list[str]
    @return: The accumulated path
    @rtype: str
    """
    return os.path.join(ts3lib.getPluginPath(), "pyTSon", *args)
예제 #12
0
 def __init__(self, tutorial, parent=None):
     super(QDialog, self).__init__(parent)
     # path to .ui-file
     setupUi(
         self,
         os.path.join(getPluginPath(), "pyTSon", "scripts", "tutorial",
                      "dialog.ui"))
     self.setWindowTitle("Tutorial")
     # connect a function to the submit button
     # btn_submit cause we named the button like that in Qt Creator
     self.btn_submit.clicked.connect(self.action)
예제 #13
0
    def __init__(self, parent):
        super(QDialog, self).__init__(parent)
        setupUi(
            self,
            os.path.join(ts3.getPluginPath(), "pyTSon", "ressources",
                         "report.ui"), self.CONF_WIDGETS)
        self.setupList()

        self.reasons.connect(
            "currentItemChanged(QListWidgetItem*, QListWidgetItem*)",
            self.onReasonListCurrentItemChanged)
예제 #14
0
    def __init__(self):
        self.clients = {}
        self.buf = {}

        self.server = QLocalServer()
        self.server.connect("newConnection()", self.onNewConnection)

        path = os.path.join(ts3lib.getPluginPath(), "pyTSon", "ipcsocket")
        QLocalServer.removeServer(path)
        if not self.server.listen(path):
            raise Exception("Error opening local socket (%s)" % path)
예제 #15
0
 def __init__(self, info, schid, atype, selectedItemID, parent=None):
     super(QDialog, self).__init__(parent)
     setupUi(
         self,
         os.path.join(ts3lib.getPluginPath(), "pyTSon", "scripts", "info",
                      "variables.ui"))
     self.setAttribute(Qt.WA_DeleteOnClose)
     self.info = info
     self.schid = schid
     self.atype = atype
     self.selectedItemID = selectedItemID
     self.setupTable()
예제 #16
0
    def __init__(self, cc, parent=None):
        self.cc = cc
        super(QDialog, self).__init__(parent)
        self.setWindowIcon(
            QIcon(
                os.path.join(getPluginPath(), "pyTSon", "scripts",
                             "contactcleaner", "icon.png")))
        setupUi(
            self,
            os.path.join(getPluginPath(), "pyTSon", "scripts",
                         "contactcleaner", "main.ui"))
        self.setWindowTitle("Contact Cleaner")

        # Load version from plguin vars
        self.ui_label_version.setText("v" + cc.version)

        # Delete QDialog on Close
        self.setAttribute(Qt.WA_DeleteOnClose)

        # Disable help button
        self.setWindowFlags(self.windowFlags()
                            & ~Qt.WindowContextHelpButtonHint)

        # Button connects
        self.ui_btn_check.clicked.connect(self.check)
        self.ui_btn_clean.clicked.connect(self.clean)

        # Current time
        self.datenow_obj = datetime.datetime.now()

        # Add options to combo
        self.ui_combo_time.addItem("1 month", 1)
        self.ui_combo_time.addItem("3 month", 3)
        self.ui_combo_time.addItem("6 month", 6)
        self.ui_combo_time.addItem("1 year", 12)
        self.ui_combo_time.addItem("2 years", 24)
        self.ui_combo_time.addItem("3 years amd more", 36)
예제 #17
0
 def __init__(self):
     # noinspection PyUnresolvedReferences
     i = QApplication.instance()
     # noinspection PyUnresolvedReferences
     p = QIcon(ts3.getPluginPath() + "pyTSon/scripts/discordify/icon.png")
     for item in i.allWidgets():
         try:
             item.setWindowIcon(p)
         except:
             pass
         try:
             t = item.windowTitle.replace("TeamSpeak 3", "")
             if t and not "Discord - " in t:
                 item.setWindowTitle("Discord - " + t)
         except:
             pass
예제 #18
0
 def __init__(self, arg, parent=None):
     super(QDialog, self).__init__(parent)
     setupUi(self, os.path.join(ts3.getPluginPath(), "pyTSon", "scripts", "devTools", "editor.ui"))
     self.resize(1000, 900)
     self.setWindowTitle('Teamspeak Stylesheet Editor : : Developer Tools')
     self.stylesheet = QApplication.instance().styleSheet
     self.chatsheet = self.getWidgetByObjectName("ChatTab").findChild(QTextDocument).defaultStyleSheet
     self.html = self.getWidgetByObjectName("InfoFrame").html
     self.qssEditor.setPlainText(self.stylesheet)
     self.chatEditor.setPlainText(self.chatsheet)
     self.tplEditor.setPlainText(self.html)
     self.chatEditor.setReadOnly(True);self.tplEditor.setReadOnly(True)
     index = self.tabWidget.currentIndex
     if index == 0:
         self.btn_apply.setEnabled(True);self.btn_minify.setEnabled(True);self.btn_insert.setEnabled(True);self.btn_reset.setEnabled(True);self.chk_live.setEnabled(True)
     elif index == 1:
         self.btn_apply.setEnabled(False);self.btn_minify.setEnabled(True);self.btn_insert.setEnabled(False);self.btn_reset.setEnabled(False);self.chk_live.setEnabled(False)
     else:
         self.btn_apply.setEnabled(False);self.btn_minify.setEnabled(False);self.btn_insert.setEnabled(False);self.btn_reset.setEnabled(False);self.chk_live.setEnabled(False)
     self.lastSave = None
예제 #19
0
 def __init__(self, this, parent=None):
     try:
         self.this = this
         super(QDialog, self).__init__(parent)
         setupUi(
             self,
             path.join(ts3.getPluginPath(), "pyTSon", "scripts",
                       "ISPValidator", "settings.ui"))
         self.setWindowTitle("%s Settings" % this.name)
         self.chk_debug.setChecked(this.cfg.getboolean("general", "debug"))
         if this.cfg.getboolean("general", "whitelist"):
             self.chk_whitelist.setChecked(True)
         else:
             self.chk_blacklist.setChecked(True)
         if this.cfg.getboolean("main", "kickonly"):
             self.chk_kick.setChecked(True)
         else:
             self.chk_ban.setChecked(True)
         if this.cfg.getboolean("failover", "kickonly"):
             self.chk_kick_2.setChecked(True)
         else:
             self.chk_ban_2.setChecked(True)
         self.bantime.setValue(int(this.cfg["main"]["bantime"]))
         self.bantime_2.setValue(int(this.cfg["failover"]["bantime"]))
         self.reason.setText(this.cfg["main"]["reason"])
         self.reason_2.setText(this.cfg["failover"]["reason"])
         self.api_main.setText(this.cfg["api"]["main"])
         self.api_fallback.setText(this.cfg["api"]["fallback"])
         if this.cfg.getboolean("failover", "enabled"):
             self.chk_failover.setChecked(True)
         for event, value in this.cfg["events"].items():
             _item = QListWidgetItem(self.lst_events)
             _item.setToolTip(value)
             _item.setText(event.title())
             if value == "True": _item.setCheckState(Qt.Checked)
             else: _item.setCheckState(Qt.Unchecked)
     except:
         ts3.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                        "PyTSon", 0)
예제 #20
0
class rotateNick(ts3plugin):
    name = "Rotate Nickname"
    apiVersion = 22
    requestAutoload = False
    version = "1.0"
    author = "Bluscream"
    description = "Converts your nickname into an ugly marquee\n\nCheck out https://r4p3.net/forums/plugins.68/ for more plugins."
    offersConfigure = False
    commandKeyword = ""
    infoTitle = None
    menuItems = [(ts3defines.PluginMenuType.PLUGIN_MENU_TYPE_GLOBAL, 0,
                  "Toggle rotating nickname", "")]
    hotkeys = []
    timer = None
    debug = False
    max = ts3defines.TS3_MAX_SIZE_CLIENT_NICKNAME_NONSDK
    nick = "TeamspeakUser"
    seperator = "꧂"
    schid = 0
    i = max - 2
    b = 0
    dlg = None
    ini = path.join(ts3lib.getPluginPath(), "pyTSon", "scripts", "rotateNick",
                    "config.ini")
    config = configparser.ConfigParser()

    def separator(self, sep=None):
        if sep: self.config.set('general', 'separator', sep.replace(" ", "\s"))
        else: return self.config.get('general', 'separator').replace("\s", " ")

    @staticmethod
    def timestamp():
        return '[{:%Y-%m-%d %H:%M:%S}] '.format(datetime.now())

    def __init__(self):
        if path.isfile(self.ini):
            self.config.read(self.ini)
        else:
            self.config["general"] = {
                "cfgver": "1",
                "debug": "False",
                "nick": "TeamspeakUser",
                "customNick": "False",
                "interval": "1000",
                "separator": " "
            }
            with open(self.ini, 'w') as configfile:
                self.config.write(configfile)

        # if self.timer is None:
        self.timer = QTimer()
        self.timer.timeout.connect(self.tick)
        if self.debug:
            ts3lib.printMessageToCurrentTab(
                "{0}[color=orange]{1}[/color] Plugin for pyTSon by [url=https://github.com/{2}]{2}[/url] loaded."
                .format(self.timestamp(), self.name, self.author))

    def stop(self):
        self.stopTimer()

    def onMenuItemEvent(self, schid, atype, menuItemID, selectedItemID):
        if menuItemID == 0:
            if hasattr(self.timer, "isActive") and self.timer.isActive():
                self.stopTimer()
            else:
                self.schid = schid
                if not self.dlg: self.dlg = dialog(self)
                self.dlg.show()
                self.dlg.raise_()
                self.dlg.activateWindow()

    def startTimer(self, interval=1000, nick=None):
        try:
            self.nick = nick
            # if len(nick) > self.max-2: errorMsgBox("Error", "Nickname must be %s chars or below!"%self.max); return
            self.i = self.max - 2
            self.b = 0
            # step = inputBox(self.name, 'Interval in Milliseconds:')
            # if step: interval = int(step)
            # else: interval = 300
            self.timer.start(interval)
            ts3lib.printMessageToCurrentTab('Timer started!')
        except:
            from traceback import format_exc
            ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                              "pyTSon", 0)

    def stopTimer(self):
        if hasattr(self.timer, "isActive") and self.timer.isActive():
            self.timer.stop()
            # self.timer = None
            ts3lib.setClientSelfVariableAsString(
                self.schid, ts3defines.ClientProperties.CLIENT_NICKNAME,
                self._nick)
            ts3lib.flushClientSelfUpdates(self.schid)
            ts3lib.printMessageToCurrentTab('Timer stopped!')

    def tick(self):
        try:
            if self.schid == 0: return
            max = self.max - 1
            _nick = list(self.nick)
            if self.i == (len(_nick) * -1) + 2:
                self.i = max
                self.b = 0
            self.i -= 1
            self.b += 1
            # ts3lib.printMessageToCurrentTab("self.i == %s | self.b == %s"%(self.i,self.b))
            count = 0
            newnick = ["!"]

            for k in range(0, self.i):
                newnick.append(self.separator())
                count += 1

            if self.i > 1:
                for k in range(0, self.b):
                    if k < len(_nick) and k < max:
                        newnick.append(_nick[k])
                        # ts3lib.printMessageToCurrentTab("1: {} | 2: {} | 3: {}".format(0, self.b, self._nick[k]))
                        count += 1
                    else:
                        pass
                #for k in range(count, max):
                #newnick.append(separator())
            else:
                for k in range(self.i * -1, len(_nick)):
                    if k != -1 and count < max:
                        newnick.append(_nick[k])
                        count += 1
                #for k in range(count, max):
                #newnick.append(self.separator())
            # newnick.append("!")
            _newnick = ''.join(newnick)
            if _newnick is None: return
            # ts3lib.printMessageToCurrentTab("length: {} | newnick: \"{}\"".format(len(_newnick), _newnick))
            ts3lib.setClientSelfVariableAsString(
                self.schid, ts3defines.ClientProperties.CLIENT_NICKNAME,
                _newnick)
            ts3lib.flushClientSelfUpdates(self.schid)
        except:
            from traceback import format_exc
            ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                              "pyTSon", 0)
예제 #21
0
ownCID = owncid
#if "aaa_ts3Ext" in PluginHost.active: ts3host = PluginHost.active["aaa_ts3Ext"].ts3host
#else: ts3host = ts3Ext.ts3SessionHost(next(iter(PluginHost.active.values())))

print('(pyTSon v{} on {} | Console started at: {:%Y-%m-%d %H:%M:%S})'.format(
    pytson.getVersion(), pytson.platformstr(), datetime.now()))
print("Client curAPI: {} | LibVer: {} | LibVerNum: {}".format(
    pytson.getCurrentApiVersion(), ts3lib.getClientLibVersion(),
    ts3lib.getClientLibVersionNumber()))
print("Python {} {} API: {}".format(sys.platform, sys.version,
                                    sys.api_version))
print("sys.executable: %s" % sys.executable)
print("ts3lib.getAppPath(): %s" % ts3lib.getAppPath())
print("ts3lib.getConfigPath(): %s" % ts3lib.getConfigPath())
print("ts3lib.getResourcesPath(): %s" % ts3lib.getResourcesPath())
print("ts3lib.getPluginPath(): %s" % ts3lib.getPluginPath())
print("pytson.getConfigPath(): %s" % pytson.getConfigPath())
print("pytson.getPluginPath(): %s" % pytson.getPluginPath())
print("bluscream.getScriptPath(): %s" % getScriptPath("console"))
i = 0
for item in sys.path:
    print('sys.path[{}]"{}"'.format(i, item))
    i += 1
print("")
print(sys.flags)
print("")


class testClass(object):
    def __init__():
        pass
예제 #22
0
class autoFlee(ts3plugin):
    name = "Auto Flee"
    apiVersion = 22
    requestAutoload = True
    version = "1.0"
    author = "Bluscream"
    description = "Deny others to move you around."
    offersConfigure = True
    commandKeyword = ""
    infoTitle = None
    menuItems = [(ts3defines.PluginMenuType.PLUGIN_MENU_TYPE_GLOBAL, 0,
                  "Toggle " + name, ""),
                 (ts3defines.PluginMenuType.PLUGIN_MENU_TYPE_CHANNEL, 0,
                  "AutoFlee", ""),
                 (ts3defines.PluginMenuType.PLUGIN_MENU_TYPE_CLIENT, 0,
                  "AutoFlee", "")]
    hotkeys = []
    config = configparser.ConfigParser()
    cids = []
    clids = []
    ini = path.join(ts3lib.getPluginPath(), "pyTSon", "scripts", "autoFlee",
                    "cfg", "settings.ini")

    @staticmethod
    def timestamp():
        return '[{:%Y-%m-%d %H:%M:%S}] '.format(datetime.now())

    def __init__(self):
        _class = self.__class__.__bases__[0]
        if path.isfile(self.ini):
            self.config.read(self.ini)
            if not self.config.has_section('general'):
                self.config.add_section('general')
                self.config.set('general', 'enabled', "False")
                self.config.set('general', 'debug', "False")
                self.config.set('general', 'cids', "")
                self.config.set('general', 'clids', "")
        else:
            self.config['general'] = {
                "enabled": "False",
                "debug": "False",
                "cids": "",
                "clids": ""
            }
        with open(self.ini, 'w') as configfile:
            self.config.write(configfile)
        self.cids = self.config.get('general', 'cids').split(',')
        # self.clids = self.config.get('general', 'clids').split(',')
        if self.config.getboolean("general", "debug"):
            ts3lib.printMessageToCurrentTab(
                "{0}[color=orange]{1}[/color] Plugin for pyTSon by [url=https://github.com/{2}]{2}[/url] loaded."
                .format(self.timestamp(), self.name, self.author))

    def stop(self):
        # for var in ['cids', 'clids']:
        # _var = self.config.get('general', var)
        self.config.set('general', 'cids',
                        ','.join(map(str, self.cids)).replace("'',", ''))
        self.config.set('general', 'clids',
                        ','.join(map(str, self.clids)).replace("'',", ''))
        with open(self.ini, 'w') as configfile:
            self.config.write(configfile)

    def configure(self, qParentWidget):
        try:
            d = dict()
            d['enabled'] = (ValueType.boolean, "Enabled",
                            self.config['general']['enabled'] == "True", None,
                            None)
            d['debug'] = (ValueType.boolean, "Debug",
                          self.config['general']['debug'] == "True", None,
                          None)
            d['cids'] = (ValueType.string, "CIDS:",
                         self.config['general']['cids'], None, 1)
            d['clids'] = (ValueType.string, "CLIDS:",
                          self.config['general']['clids'], None, 1)
            getValues(None, self.name + " Settings", d,
                      self.configDialogClosed)
        except:
            from traceback import format_exc
            try:
                ts3lib.logMessage(format_exc(),
                                  ts3defines.LogLevel.LogLevel_ERROR,
                                  "PyTSon::" + self.name, 0)
            except:
                print("Error in " + self.name + ".configure: " + format_exc())

    def configDialogClosed(self, r, vals):
        if r == QDialog.Accepted:
            self.cfg['general'] = {
                "enabled": str(vals["enabled"]),
                "debug": str(vals["debug"]),
                "cids": vals["debug"],
                "clids": vals["clids"]
            }
            with open(self.ini, 'w') as configfile:
                self.cfg.write(configfile)

    def onMenuItemEvent(self, schid, atype, menuItemID, selectedItemID):
        if atype == ts3defines.PluginMenuType.PLUGIN_MENU_TYPE_GLOBAL and menuItemID == 0:
            self.config.set("general", "enabled",
                            not self.config.getboolean("general", "enabled"))
            ts3lib.printMessageToCurrentTab(
                "{0}Set {1} to [color=yellow]{2}[/color]".format(
                    self.timestamp(), self.name,
                    self.config.getboolean("general", "enabled")))
        elif atype == ts3defines.PluginMenuType.PLUGIN_MENU_TYPE_CHANNEL and menuItemID == 0:
            if str(selectedItemID) in self.cids:
                self.cids.remove(str(selectedItemID))
            else:
                self.cids.append(str(selectedItemID))
            ts3lib.printMessageToCurrentTab(
                "{0} {1}> Channels to flee to: {2}".format(
                    self.timestamp(), self.name, self.cids))
        elif atype == ts3defines.PluginMenuType.PLUGIN_MENU_TYPE_CLIENT and menuItemID == 0:
            if selectedItemID in self.clids: self.clids.remove(selectedItemID)
            else: self.clids.append(selectedItemID)
            ts3lib.printMessageToCurrentTab(
                "{0} {1}> Clients to flee from: {2}".format(
                    self.timestamp(), self.name, self.cids))

    def onClientMoveEvent(self, schid, clientID, oldChannelID, newChannelID,
                          visibility, moveMessage):
        if not self.config.getboolean("general", "enabled"): return
        if not str(clientID) in self.clids: return
        (err, ownID) = ts3lib.getClientID(schid)
        if clientID == ownID: return
        (err, ownCID) = ts3lib.getChannelOfClient(schid, clientID)
        if newChannelID != ownCID: return
        chan = 0
        while chan <= 0 or chan == newChannelID:
            chan = choice(self.cids)
        ts3lib.requestClientMove(schid, ownID, chan, "123")
예제 #23
0
 def __init__(self,this, parent=None):
     super(QDialog, self).__init__(parent)
     setupUi(self, os.path.join(ts3.getPluginPath(), "pyTSon", "scripts", "devTools", "test.ui"))
예제 #24
0
 def __init__(self,Class,parent=None):
     self.exporter=Class
     super(QDialog, self).__init__(parent)
     setupUi(self, os.path.join(ts3lib.getPluginPath(), "pyTSon", "scripts", "exporter", "ui", "export.ui"))
     self.setWindowTitle("Which items do you want to "+exporter.action+"?")
예제 #25
0
class settings(ts3plugin):
    name = "Extended Settings"
    apiVersion = 22
    requestAutoload = False
    version = "1.0"
    author = "Bluscream"
    description = "Features:\n\n - Toggle Hostbanners\n - Toggle Hostmessages\n - Toggle Hostbuttons\n\n\nCheck out https://r4p3.net/forums/plugins.68/ for more plugins."
    offersConfigure = True
    commandKeyword = ""
    infoTitle = None
    menuItems = []
    hotkeys = []
    ini = path.join(ts3.getPluginPath(), "pyTSon", "scripts", "settings",
                    "settings.ini")
    cfg = ConfigParser()
    dlg = None
    debug = False

    @staticmethod
    def timestamp():
        return '[{:%Y-%m-%d %H:%M:%S}] '.format(datetime.now())

    def __init__(self):
        if path.isfile(self.ini):
            self.cfg.read(self.ini)
        else:
            self.cfg['general'] = {
                "hide hostbanners": "False",
                "hide hostmessages": "False",
                "hide hostbuttons": "False"
            }
            with open(self.ini, 'w') as configfile:
                self.cfg.write(configfile)
        if self.debug:
            ts3.printMessageToCurrentTab(
                "{0}[color=orange]{1}[/color] Plugin for pyTSon by [url=https://github.com/{2}]{2}[/url] loaded."
                .format(self.timestamp(), self.name, self.author))

    def checkHostButton(self):
        if self.cfg.getboolean('general', 'hide hostbuttons'):
            hostButton = self.grabWidget('HosterButton')
            if hasattr(hostButton, 'styleSheet'):
                hostButton.styleSheet = 'margin:-9999px !important;'

    def checkHostBanner(self):
        if self.cfg.getboolean('general', 'hide hostbanners'):
            banner = self.grabWidget('Banner', True)
            if hasattr(banner, 'delete'): banner.delete()

    def checkHostMessage(self):
        if self.cfg.getboolean('general', 'hide hostmessages'):
            try:
                hostMessage = self.grabWidget('MsgDialog')
                if not hostMessage == None and hostMessage == self.grabWidget(
                        'MsgDialog', True):
                    hostMessage.hide()
                    hostMessage.close()
                    hostMessage.delete()
            except:
                pass

    def onConnectStatusChangeEvent(self, serverConnectionHandlerID, newStatus,
                                   errorNumber):
        if newStatus == ts3defines.ConnectStatus.STATUS_CONNECTION_ESTABLISHING:
            self.checkHostMessage()
            self.checkHostBanner()
            self.checkHostButton()

    #def onServerUpdatedEvent(self, serverConnectionHandlerID): self.applySettings()

    def grabWidget(self, objName, byClass=False):
        for widget in QApplication.instance().allWidgets():
            try:
                if byClass and widget.className() == objName: return widget
                elif widget.objectName == objName: return widget
            except:
                from traceback import format_exc
                ts3.logMessage(format_exc(),
                               ts3defines.LogLevel.LogLevel_ERROR, "PyTSon", 0)

    def configDialogClosed(self, r, vals):
        try:
            if r == QDialog.Accepted:
                for n, v in vals.items():
                    try:
                        if not v == self.cfg.getboolean('general', n):
                            self.cfg.set('general', n, str(v))
                    except:
                        from traceback import format_exc
                        ts3.logMessage(format_exc(),
                                       ts3defines.LogLevel.LogLevel_ERROR,
                                       "PyTSon", 0)
                with open(self.ini, 'w') as configfile:
                    self.cfg.write(configfile)
                self.checkHostMessage()
                self.checkHostBanner()
                self.checkHostButton()
        except:
            from traceback import format_exc
            ts3.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                           "PyTSon", 0)

    def configure(self, qParentWidget):
        try:
            d = dict()
            for n, v in self.cfg['general'].items():
                d[n] = (ValueType.boolean, n.title(),
                        self.cfg.getboolean('general', n), None, None)
            getValues(qParentWidget, self.name, d, self.configDialogClosed)
        except:
            from traceback import format_exc
            ts3.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                           "PyTSon", 0)
예제 #26
0
class ISPValidator(ts3plugin):
    name = "ISP Validator"
    apiVersion = 22
    requestAutoload = False
    version = "1.0"
    author = "Bluscream"
    description = "This script will autokick everyone not using a whitelisted ISP.\n\n\nCheck out https://r4p3.net/forums/plugins.68/ for more plugins."
    offersConfigure = True
    commandKeyword = ""
    infoTitle = None
    menuItems = []
    hotkeys = []
    ini = path.join(ts3.getPluginPath(), "pyTSon", "scripts", "ISPValidator",
                    "settings.ini")
    cfg = ConfigParser()
    requested = 0
    schid = 0
    dlg = None
    isps = path.join(ts3.getPluginPath(), "pyTSon", "scripts", "ISPValidator",
                     "isps.txt")

    def __init__(self):
        if path.isfile(self.ini):
            self.cfg.read(self.ini)
        else:
            self.cfg['general'] = {
                "debug": "False",
                "whitelist": "True",
                "isps": self.isps
            }
            self.cfg['main'] = {
                "kickonly": "False",
                "bantime": "60",
                "reason":
                "{isp} is not a valid home Internet Service Provider!"
            }
            self.cfg['failover'] = {
                "enabled": "False",
                "kickonly": "False",
                "bantime": "60",
                "reason":
                "{isp} is not a valid home Internet Service Provider!"
            }
            self.cfg['api'] = {
                "main": "http://ip-api.com/line/{ip}?fields=isp",
                "fallback": "http://ipinfo.io/{ip}/org"
            }
            self.cfg['events'] = {
                "own client connected": "True",
                "client connected": "True",
                "client ip changed": "False"
            }
            with open(self.ini, 'w') as configfile:
                self.cfg.write(configfile)
        with open(self.cfg['general']['isps']) as f:
            self.isps = f.readlines()

    def configure(self, qParentWidget):
        try:
            if not self.dlg:
                self.dlg = SettingsDialog(self)
            self.dlg.show()
            self.dlg.raise_()
            self.dlg.activateWindow()
        except:
            ts3.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                           "PyTSon", 0)

    def onConnectStatusChangeEvent(self, serverConnectionHandlerID, newStatus,
                                   errorNumber):
        if not self.cfg.getboolean("events", "own client connected"): return
        if newStatus == ts3defines.ConnectStatus.STATUS_CONNECTION_ESTABLISHED:
            (error, ids) = ts3.getClientList(serverConnectionHandlerID)
            if error == ts3defines.ERROR_ok:
                for _in in ids:
                    (error, _type) = ts3.getClientVariableAsInt(
                        serverConnectionHandlerID, clientID,
                        ts3defines.ClientPropertiesRare.CLIENT_TYPE)
                    if error == ts3defines.ERROR_ok and _type == 0:
                        self.requested = clientID
                        self.schid = serverConnectionHandlerID
                        ts3.requestConnectionInfo(serverConnectionHandlerID,
                                                  clientID)
                    elif error == ts3defines.ERROR_ok and _type == 1:
                        return
                    else:
                        ts3.printMessageToCurrentTab(
                            "[[color=orange]WARNING[/color]] [color=red]ISPValidator could not resolve the client type of '%s'"
                            % self.clientURL(serverConnectionHandlerID,
                                             clientID))
                        return

    def onUpdateClientEvent(self, serverConnectionHandlerID, clientID,
                            invokerID, invokerName, invokerUniqueIdentifier):
        if not self.cfg.getboolean("events", "client ip changed"): return
        if not invokerID == 0: return
        (error, _type) = ts3.getClientVariableAsInt(
            serverConnectionHandlerID, clientID,
            ts3defines.ClientPropertiesRare.CLIENT_TYPE)
        if error == ts3defines.ERROR_ok and _type == 0:
            self.requested = clientID
            self.schid = serverConnectionHandlerID
            ts3.requestConnectionInfo(serverConnectionHandlerID, clientID)
        elif error == ts3defines.ERROR_ok and _type == 1:
            return
        else:
            ts3.printMessageToCurrentTab(
                "[[color=orange]WARNING[/color]] [color=red]ISPValidator could not resolve the client type of '%s'"
                % self.clientURL(serverConnectionHandlerID, clientID))
            return

    def onClientMoveEvent(self, serverConnectionHandlerID, clientID,
                          oldChannelID, newChannelID, visibility, moveMessage):
        if not self.cfg.getboolean("events", "client connected"): return
        if oldChannelID == 0:
            (error, _type) = ts3.getClientVariableAsInt(
                serverConnectionHandlerID, clientID,
                ts3defines.ClientPropertiesRare.CLIENT_TYPE)
            if error == ts3defines.ERROR_ok and _type == 0:
                self.requested = clientID
                self.schid = serverConnectionHandlerID
                ts3.requestConnectionInfo(serverConnectionHandlerID, clientID)
            elif error == ts3defines.ERROR_ok and _type == 1:
                return
            else:
                ts3.printMessageToCurrentTab(
                    "[[color=orange]WARNING[/color]] [color=red]ISPValidator could not resolve the client type of '%s'"
                    % self.clientURL(serverConnectionHandlerID, clientID))
                return

    def onConnectionInfoEvent(self, serverConnectionHandlerID, clientID):
        try:
            if not self.requested == clientID: return
            (error, ip) = ts3.getConnectionVariableAsString(
                serverConnectionHandlerID, clientID,
                ts3defines.ConnectionProperties.CONNECTION_CLIENT_IP)
            if error == ts3defines.ERROR_ok:
                self.ip = ip
                self.nwm = QNetworkAccessManager()
                self.nwm.connect("finished(QNetworkReply*)", self.onMainReply)
                self.nwm.get(
                    QNetworkRequest(
                        QUrl(self.cfg['api']['main'].replace("{ip}", ip))))
                if PluginHost.cfg.getboolean("general", "verbose"):
                    ts3.printMessageToCurrentTab(
                        self.cfg['api']['main'].replace("{ip}", ip))
            else:
                (e, msg) = ts3.getErrorMessage(error)
                ts3.printMessageToCurrentTab(
                    "[[color=orange]WARNING[/color]] [color=red]ISPValidator could not resolve the IP for '%s' (Reason: %s)"
                    %
                    (self.clientURL(serverConnectionHandlerID, clientID), msg))
        except:
            ts3.printMessageToCurrentTab(
                "[[color=orange]WARNING[/color]] [color=red]ISPValidator could not resolve the IP for '%s' (Reason: %s)"
                % (self.clientURL(serverConnectionHandlerID,
                                  clientID), format_exc()))

    def onMainReply(self, reply):
        if reply.error() == QNetworkReply.NoError:
            try:
                isp = reply.readAll().data().decode('utf-8')
                if isp.startswith('AS'): isp = isp.split(" ", 1)[1]
                if not isp or isp == "" or isp == "undefined":
                    ts3.printMessageToCurrentTab(
                        "[[color=orange]WARNING[/color]] [color=red]ISPValidator could not resolve the ISP for '%s' (Reason: %s) Falling back to %s"
                        % (self.clientURL(self.schid, self.requested),
                           format_exc(), self.cfg['api']['fallback'].replace(
                               "{ip}", self.ip)))
                    if PluginHost.cfg.getboolean("general", "verbose"):
                        ts3.printMessageToCurrentTab(
                            self.cfg['api']['fallback'].replace(
                                "{ip}", self.ip))
                    self.nwb = QNetworkAccessManager()
                    self.nwb.connect("finished(QNetworkReply*)",
                                     self.onFallbackReply)
                    self.nwb.get(
                        QNetworkRequest(
                            QUrl(self.cfg['api']['fallback'].replace(
                                "{ip}", self.ip))))
                    return
                if PluginHost.cfg.getboolean("general", "verbose"):
                    ts3.printMessageToCurrentTab(
                        "%s's ISP: %s" %
                        (self.clientURL(self.schid, self.requested), isp))
                _match = False
                for _isp in self.isps:
                    if isp == _isp: _match = True
                if self.cfg.getboolean('general', 'whitelist') and not _match:
                    if self.cfg.getboolean('main', 'kickonly'):
                        ts3.requestClientKickFromServer(
                            self.schid, self.requested,
                            "%s is not a valid Internet Service Provider!" %
                            isp)
                        self.requested = 0
                    else:
                        ts3.banclient(
                            self.schid, self.requested, 60,
                            "%s is not a valid Internet Service Provider!" %
                            isp)
                        self.requested = 0
                elif not self.cfg.getboolean('general',
                                             'whitelist') and _match:
                    if self.cfg.getboolean('main', 'kickonly'):
                        ts3.requestClientKickFromServer(
                            self.schid, self.requested,
                            "%s is not a valid Internet Service Provider!" %
                            isp)
                        self.requested = 0
                    else:
                        ts3.banclient(
                            self.schid, self.requested, 60,
                            "%s is not a valid Internet Service Provider!" %
                            isp)
                        self.requested = 0
            except:
                try:
                    ts3.printMessageToCurrentTab(
                        "[[color=orange]WARNING[/color]] [color=red]ISPValidator could not resolve the ISP for '%s' (Reason: %s) Falling back to %s"
                        % (self.clientURL(self.schid, self.requested),
                           format_exc(), self.cfg['api']['fallback'].replace(
                               "{ip}", self.ip)))
                    if PluginHost.cfg.getboolean("general", "verbose"):
                        ts3.printMessageToCurrentTab(
                            self.cfg['api']['fallback'].replace(
                                "{ip}", self.ip))
                    self.nwb = QNetworkAccessManager()
                    self.nwb.connect("finished(QNetworkReply*)",
                                     self.onFallbackReply)
                    self.nwb.get(
                        QNetworkRequest(
                            QUrl(self.cfg['api']['fallback'].replace(
                                "{ip}", self.ip))))
                except:
                    ts3.printMessageToCurrentTab(format_exc())
        else:
            ts3.printMessageToCurrentTab(
                "[[color=orange]WARNING[/color]] [color=red]ISPValidator could not resolve the ISP for '%s' (Reason: %s) Falling back to %s"
                % (self.clientURL(self.schid, self.requested),
                   reply.errorString(), self.cfg['api']['fallback'].replace(
                       "{ip}", self.ip)))
            if PluginHost.cfg.getboolean("general", "verbose"):
                ts3.printMessageToCurrentTab(
                    self.cfg['api']['fallback'].replace("{ip}", self.ip))
            self.nwb = QNetworkAccessManager()
            self.nwb.connect("finished(QNetworkReply*)", self.onFallbackReply)
            self.nwb.get(
                QNetworkRequest(
                    QUrl(self.cfg['api']['fallback'].replace("{ip}",
                                                             self.ip))))
        reply.deleteLater()

    def onFallbackReply(self, reply):
        if reply.error() == QNetworkReply.NoError:
            try:
                isp = reply.readAll().data().decode('utf-8')
                if isp.startswith('AS'): isp = isp.split(" ", 1)[1]
                if not isp or isp == "" or isp == "undefined":
                    ts3.printMessageToCurrentTab(
                        "[[color=orange]WARNING[/color]] [color=red]ISPValidator could not resolve the ISP for '%s' (Reason: %s)"
                        % (self.clientURL(self.schid,
                                          self.requested), format_exc()))
                    if self.cfg.getboolean("failover", "enabled"):
                        if self.cfg.getboolean('failover', 'kickonly'):
                            ts3.requestClientKickFromServer(
                                self.schid, self.requested,
                                self.cfg['failover']['reason'].replace(
                                    '{isp}', isp))
                        else:
                            ts3.banclient(
                                self.schid, self.requested,
                                int(self.cfg['failover']['bantime']),
                                self.cfg['failover']['reason'].replace(
                                    '{isp}', isp))
                        self.requested = 0
                        reply.deleteLater()
                        return
                if PluginHost.cfg.getboolean("general", "verbose"):
                    ts3.printMessageToCurrentTab(
                        "%s's ISP: %s" %
                        (self.clientURL(self.schid, self.requested), isp))
                _match = False
                for _isp in self.isps:
                    if isp == _isp: _match = True
                if self.cfg.getboolean('general', 'whitelist') and not _match:
                    if self.cfg.getboolean('main', 'kickonly'):
                        ts3.requestClientKickFromServer(
                            self.schid, self.requested,
                            "%s is not a valid Internet Service Provider!" %
                            isp)
                        self.requested = 0
                    else:
                        ts3.banclient(
                            self.schid, self.requested, 60,
                            "%s is not a valid Internet Service Provider!" %
                            isp)
                        self.requested = 0
                elif not self.cfg.getboolean('general',
                                             'whitelist') and _match:
                    if self.cfg.getboolean('main', 'kickonly'):
                        ts3.requestClientKickFromServer(
                            self.schid, self.requested,
                            "%s is not a valid Internet Service Provider!" %
                            isp)
                        self.requested = 0
                    else:
                        ts3.banclient(
                            self.schid, self.requested, 60,
                            "%s is not a valid Internet Service Provider!" %
                            isp)
                        self.requested = 0
            except:
                ts3.printMessageToCurrentTab(
                    "[[color=orange]WARNING[/color]] [color=red]ISPValidator could not resolve the ISP for '%s' (Reason: %s)"
                    %
                    (self.clientURL(self.schid, self.requested), format_exc()))
                if self.cfg.getboolean("failover", "enabled"):
                    if self.cfg.getboolean('failover', 'kickonly'):
                        ts3.requestClientKickFromServer(
                            self.schid, self.requested,
                            self.cfg['failover']['reason'].replace(
                                '{isp}', isp))
                    else:
                        ts3.banclient(
                            self.schid, self.requested,
                            int(self.cfg['failover']['bantime']),
                            self.cfg['failover']['reason'].replace(
                                '{isp}', isp))
        else:
            ts3.printMessageToCurrentTab(
                "[[color=orange]WARNING[/color]] [color=red]ISPValidator could not resolve the ISP for '%s' (Reason: %s)"
                % (self.clientURL(self.schid,
                                  self.requested), reply.errorString()))
            if self.cfg.getboolean("failover", "enabled"):
                if self.cfg.getboolean('failover', 'kickonly'):
                    ts3.requestClientKickFromServer(
                        self.schid, self.requested,
                        self.cfg['failover']['reason'].replace('{isp}', isp))
                else:
                    ts3.banclient(
                        self.schid, self.requested,
                        int(self.cfg['failover']['bantime']),
                        self.cfg['failover']['reason'].replace('{isp}', isp))
        self.requested = 0
        reply.deleteLater()

    def clientURL(self,
                  schid=None,
                  clid=1,
                  uid=None,
                  nickname=None,
                  encodednick=None):
        if schid == None:
            try:
                schid = ts3.getCurrentServerConnectionHandlerID()
            except:
                pass
        if uid == None:
            try:
                (error, uid) = ts3.getClientVariableAsString(
                    schid, clid,
                    ts3defines.ClientProperties.CLIENT_UNIQUE_IDENTIFIER)
            except:
                pass
        if nickname == None:
            try:
                (error, nickname) = ts3.getClientDisplayName(schid, clid)
            except:
                nickname = uid
        if encodednick == None:
            try:
                encodednick = urlencode(nickname)
            except:
                pass
        return "[url=client://%s/%s~%s]%s[/url]" % (clid, uid, encodednick,
                                                    nickname)
예제 #27
0
class dynamicAvatar(ts3plugin):
    shortname = "AC"
    name = "Dynamic Avatar Changer"
    requestAutoload = False
    version = "1.0"
    apiVersion = 22
    author = "Bluscream"
    description = "Changes your avatar for you."
    offersConfigure = True
    commandKeyword = ""
    infoTitle = None
    menuItems = [(ts3defines.PluginMenuType.PLUGIN_MENU_TYPE_GLOBAL, 0,
                  "Refresh avatar",
                  path.join(ts3lib.getPluginPath(), "pyTSon", "scripts",
                            "dynamicAvatar", "gfx", "manual.png")),
                 (ts3defines.PluginMenuType.PLUGIN_MENU_TYPE_GLOBAL, 1,
                  "Toggle Timer", '')]
    hotkeys = []
    ini = path.join(getPluginPath(), "scripts", "dynamicAvatar",
                    "settings.ini")
    config = ConfigParser()
    timer = QTimer()
    int = 0

    def timestamp(self):
        return '[{:%Y-%m-%d %H:%M:%S}] '.format(datetime.now())

    def __init__(self):
        if path.isfile(self.ini): self.config.read(self.ini)
        else:
            self.config['GENERAL'] = {
                "debug": "False",
                "imgurl": "",
                "imgpath": "",
                "mode": "url",
                "refresh": "60"
            }
            with open(self.ini, 'w') as configfile:
                self.config.write(configfile)
        self.timer.timeout.connect(self.tick)
        if self.config.getboolean('GENERAL', 'debug'):
            ts3lib.printMessageToCurrentTab(
                "{0}[color=orange]{1}[/color] Plugin for pyTSon by [url=https://github.com/{2}]{2}[/url] loaded."
                .format(self.timestamp(), self.name, self.author))

    def tick(self, schid=0):
        schid = ts3lib.getCurrentServerConnectionHandlerID()
        self.int += 1
        ts3lib.printMessageToCurrentTab('Tick %s' % self.int)
        if self.config.get('GENERAL', 'mode') == 'url': self.urlAvatar(schid)
        else: self.pathAvatar(schid)

    def configure(self, qParentWidget):
        try:
            self.dlg = SettingsDialog(self)
            self.dlg.show()
        except:
            from traceback import format_exc
            try:
                ts3lib.logMessage(format_exc(),
                                  ts3defines.LogLevel.LogLevel_ERROR,
                                  "PyTSon::" + self.name, 0)
            except:
                print("Error in " + self.name + ".configure: " + format_exc())

    def onMenuItemEvent(self, schid, atype, menuItemID, selectedItemID):
        try:
            if atype == ts3defines.PluginMenuType.PLUGIN_MENU_TYPE_GLOBAL:
                if menuItemID == 0:
                    if self.config.get('GENERAL', 'mode') == "url":
                        self.urlAvatar(schid)
                    elif self.config.get('GENERAL', 'mode') == "path":
                        self.pathAvatar(schid)
                elif menuItemID == 1:
                    if self.timer.isActive():
                        self.timer.stop()
                        ts3lib.printMessageToCurrentTab('Timer stopped!')
                    else:
                        self.timer.start(
                            int(self.config.get('GENERAL', 'refresh')) * 1000)
                        ts3lib.printMessageToCurrentTab('Timer started!')
        except:
            try:
                from traceback import format_exc
                ts3lib.logMessage(format_exc(),
                                  ts3defines.LogLevel.LogLevel_ERROR,
                                  "PyTSon Script", 0)
            except:
                try:
                    from traceback import format_exc
                    print(format_exc())
                except:
                    print("Unknown Error")

    def urlAvatar(self, schid):
        try:
            self.nwm = QNetworkAccessManager()
            self.nwm.connect("finished(QNetworkReply*)", self.onNetworkReply)
            self.schid = schid
            print("%s" % self.config.get('GENERAL', 'imgurl'))
            self.nwm.get(
                QNetworkRequest(QUrl(self.config.get('GENERAL', 'imgurl'))))
        except:
            from traceback import format_exc
            try:
                ts3lib.logMessage(format_exc(),
                                  ts3defines.LogLevel.LogLevel_ERROR,
                                  "PyTSon Script", 0)
            except:
                print(format_exc())

    def onNetworkReply(
        self, reply
    ):  #http://stackoverflow.com/questions/41712636/qnetworkrequest-for-generated-images
        try:
            print("Error: %s (%s)" % (reply.error(), reply.errorString()))
            print("Content-Type: %s" %
                  reply.header(QNetworkRequest.ContentTypeHeader))
            try:
                print("Content: %s" % reply.readAll())
            except:
                pass
            #if reply.header(QNetworkRequest.ContentTypeHeader) == "image/jpeg":
            imgraw = reply.readAll()  #.data()#.decode('utf-8')
            temp_dir = gettempdir()
            filename = self.generateAvatarFileName(self.schid)
            tmp = path.join(temp_dir, filename)
            fn = QFile(tmp)
            fn.open(QIODevice.WriteOnly)
            fn.write(imgraw)
            fn.close
            #with open(tmp, 'wb') as f: f.write(imgraw)
            ts3lib.logMessage("Uploading %s as new avatar." % tmp,
                              ts3defines.LogLevel.LogLevel_INFO,
                              "PyTSon Script", 0)
            self.uploadAvatar(self.schid, tmp, filename)
        except:
            from traceback import format_exc
            try:
                ts3lib.logMessage(format_exc(),
                                  ts3defines.LogLevel.LogLevel_ERROR,
                                  "PyTSon Script", 0)
            except:
                print(format_exc())
        reply.deleteLater()

    def pathAvatar(self, schid):
        try:
            _path = self.config.get('GENERAL', 'imgpath')
            img = path.join(
                _path,
                random.choice([
                    x for x in listdir(_path)
                    if path.isfile(path.join(_path, x))
                ]))
            if not self.getFileExtension(img) in [
                    'bmp', 'gif', 'jpeg', 'jpg', 'pbm', 'pgm', 'png', 'ppm',
                    'xbm', 'xpm', None
            ]:
                self.pathAvatar(schid)
                return
            temp_dir = gettempdir()
            filename = self.generateAvatarFileName(schid)
            tmp = path.join(temp_dir, filename)
            copy2(img, tmp)
            ts3lib.logMessage("Uploading %s as new avatar." % img,
                              ts3defines.LogLevel.LogLevel_INFO,
                              "PyTSon Script", 0)
            self.uploadAvatar(schid, tmp, filename)
        except:
            from traceback import format_exc
            try:
                ts3lib.logMessage(format_exc(),
                                  ts3defines.LogLevel.LogLevel_ERROR,
                                  "PyTSon Script", 0)
            except:
                print(format_exc())

    def uploadAvatar(self, schid, img, filename=""):
        try:
            img = path.abspath(img)
            self.tmp = img
            if filename == "": filename = self.generateAvatarFileName(schid)
            imgdir = path.dirname(img) + path.sep
            self.retcode = ts3lib.createReturnCode()
            (error, ftid) = ts3lib.sendFile(schid, 0, "",
                                            "/avatar/" + filename, True, False,
                                            imgdir, self.retcode)
        except:
            try:
                from traceback import format_exc
                ts3lib.logMessage(format_exc(),
                                  ts3defines.LogLevel.LogLevel_ERROR,
                                  "PyTSon Script", 0)
            except:
                try:
                    from traceback import format_exc
                    print(format_exc())
                except:
                    print("Unknown Error")

    def setAvatar(self, schid, img):
        ts3lib.setClientSelfVariableAsString(
            schid, ts3defines.ClientPropertiesRare.CLIENT_FLAG_AVATAR,
            self.getMd5FromFile(img))
        ts3lib.flushClientSelfUpdates(schid)

    def generateAvatarFileName(self, schid):
        (error, ownID) = ts3lib.getClientID(schid)
        (error, ownUID) = ts3lib.getClientVariableAsString(
            schid, ownID, ts3defines.ClientProperties.CLIENT_UNIQUE_IDENTIFIER)
        ownUID = ownUID.encode('ascii')
        return "avatar_" + b64encode(ownUID).decode("ascii").split('=')[0]

    def getMd5FromFile(self, file):
        hash_md5 = md5()
        with open(file, "rb") as f:
            #f = iopen(file, 'rb')
            for chunk in iter(lambda: f.read(4096), b""):
                hash_md5.update(chunk)
        #f.close()
        return hash_md5.hexdigest()

    def getFileExtension(self, filename):
        basename = path.basename(filename)  # os independent
        ext = '.'.join(basename.split('.')[1:])
        return ext if ext else None

    def onServerErrorEvent(self, schid, errorMessage, error, returnCode,
                           extraMessage):
        if hasattr(self, "retcode") and self.retcode == returnCode:
            self.retcode = None
            self.setAvatar(schid, self.tmp)
        try:
            remove(self.tmp)
            self.tmp = None
        except:
            QTimer.singleShot(500, self.deltmp)

    def deltmp(self):
        try:
            f = iopen(self.tmp)
            f.close()
        except:
            pass
        try:
            remove(self.tmp)
            self.tmp = None
        except:
            QTimer.singleShot(1000, self.tmp)

    # def onFileTransferStatusEvent(self, ftid, status, statusMessage, remotefileSize, schid): # Doesn't work in pyTSon
    #     try:
    #         print("test")
    #         print(str("#"+ftid+": "+status))
    #     except:
    #         try: from traceback import format_exc;ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "PyTSon Script", 0)
    #         except:
    #             try: from traceback import format_exc;print(format_exc())
    #             except: print("Unknown Error")

    def onConnectStatusChangeEvent(self, schid, newStatus, errorNumber):
        if newStatus == ts3defines.ConnectStatus.STATUS_CONNECTION_ESTABLISHED:
            if ts3lib.getServerVariableAsString(
                    schid, ts3defines.VirtualServerProperties.
                    VIRTUALSERVER_UNIQUE_IDENTIFIER
            ) == "QTRtPmYiSKpMS8Oyd4hyztcvLqU=":
                return
            # if not self.timer.isActive(): self.timer.start(int(self.config.get('GENERAL', 'refresh'))*1000);
        elif newStatus == ts3defines.ConnectStatus.STATUS_DISCONNECTED:
            if self.timer.isActive(): self.timer.stop()
예제 #28
0
 def __init__(self, info, parent=None):
     super(QDialog, self).__init__(parent)
     setupUi(
         self,
         os.path.join(ts3.getPluginPath(), "pyTSon", "scripts", "info",
                      "settings.ui"))
     self.setAttribute(Qt.WA_DeleteOnClose)
     self.setWindowTitle("Extended Info Settings")
     self.chk_debug.setChecked(info.cfg.getboolean('general', 'Debug'))
     self.chk_colored.setChecked(info.cfg.getboolean('general', 'Colored'))
     self.chk_arsv.setChecked(
         info.cfg.getboolean('general', 'Autorequest Server Variables'))
     self.chk_arcv.setChecked(
         info.cfg.getboolean('general', 'Autorequest Client Variables'))
     for name, value in info.cfg['VirtualServerProperties'].items():
         _item = QListWidgetItem(self.lst_server)
         _item.setToolTip(name)
         _item.setStatusTip('VirtualServerProperties')
         if value.lower() == "true": _item.setCheckState(Qt.Checked)
         else: _item.setCheckState(Qt.Unchecked)
         _item.setText(
             name.replace('VIRTUALSERVER_', '').replace('_', ' ').title())
     for name, value in info.cfg['VirtualServerPropertiesRare'].items():
         _item = QListWidgetItem(self.lst_server)
         _item.setToolTip(name)
         _item.setStatusTip('VirtualServerPropertiesRare')
         if value.lower() == "true": _item.setCheckState(Qt.Checked)
         else: _item.setCheckState(Qt.Unchecked)
         _item.setText(
             name.replace('VIRTUALSERVER_', '').replace('_', ' ').title())
     for name, value in info.cfg['ChannelProperties'].items():
         _item = QListWidgetItem(self.lst_channel)
         _item.setToolTip(name)
         _item.setStatusTip('ChannelProperties')
         if value.lower() == "true": _item.setCheckState(Qt.Checked)
         else: _item.setCheckState(Qt.Unchecked)
         _item.setText(
             name.replace('CHANNEL_', '').replace('_', ' ').title())
     for name, value in info.cfg['ChannelPropertiesRare'].items():
         _item = QListWidgetItem(self.lst_channel)
         _item.setToolTip(name)
         _item.setStatusTip('ChannelPropertiesRare')
         if value.lower() == "true": _item.setCheckState(Qt.Checked)
         else: _item.setCheckState(Qt.Unchecked)
         _item.setText(
             name.replace('CHANNEL_', '').replace('_', ' ').title())
     for name, value in info.cfg['ClientProperties'].items():
         _item = QListWidgetItem(self.lst_client)
         _item.setToolTip(name)
         _item.setStatusTip('ClientProperties')
         if value.lower() == "true": _item.setCheckState(Qt.Checked)
         else: _item.setCheckState(Qt.Unchecked)
         _item.setText(
             name.replace('CLIENT_', '').replace('_', ' ').title())
     for name, value in info.cfg['ClientPropertiesRare'].items():
         _item = QListWidgetItem(self.lst_client)
         _item.setToolTip(name)
         _item.setStatusTip('ClientPropertiesRare')
         if value.lower() == "true": _item.setCheckState(Qt.Checked)
         else: _item.setCheckState(Qt.Unchecked)
         _item.setText(
             name.replace('CLIENT_', '').replace('_', ' ').title())
     for name, value in info.cfg['ConnectionProperties'].items():
         _item = QListWidgetItem(self.lst_client)
         _item.setToolTip(name)
         _item.setStatusTip('ConnectionProperties')
         if value.lower() == "true": _item.setCheckState(Qt.Checked)
         else: _item.setCheckState(Qt.Unchecked)
         _item.setText(
             name.replace('CONNECTION_', '').replace('_', ' ').title())
     for name, value in info.cfg['ConnectionPropertiesRare'].items():
         _item = QListWidgetItem(self.lst_client)
         _item.setToolTip(name)
         _item.setStatusTip('ConnectionPropertiesRare')
         if value.lower() == "true": _item.setCheckState(Qt.Checked)
         else: _item.setCheckState(Qt.Unchecked)
         _item.setText(
             name.replace('CONNECTION_', '').replace('_', ' ').title())
     self.info = info
예제 #29
0
class cfgDialog(ts3plugin):
    name = "Config Dialog Examples"
    apiVersion = 22
    requestAutoload = False
    version = "1.0"
    author = "Bluscream"
    description = "Just to show some ways to implement a Config Dialog using ConfigParser and Qt.\n\n\nCheck out https://r4p3.net/forums/plugins.68/ for more plugins."
    offersConfigure = True
    commandKeyword = ""
    infoTitle = None
    menuItems = []
    hotkeys = []
    ini = path.join(ts3.getPluginPath(), "pyTSon", "scripts", "cfgDialog.ini")
    cfg = ConfigParser()

    def __init__(self):
        if path.isfile(self.ini):
            self.cfg.read(self.ini)
        else:
            self.cfg['general'] = {"Example string": "Hello World :)"}
            with open(self.ini, 'w') as configfile:
                self.cfg.write(configfile)

    def configDialogClosed(self, r, vals):
        # Start getValues method +
        try:
            if r == QDialog.Accepted:
                for name, val in vals.items():
                    try:
                        if not val == self.cfg.getboolean('general', name):
                            self.cfg.set('general', str(name), str(val))
                    except:
                        from traceback import format_exc
                        ts3.logMessage(format_exc(),
                                       ts3defines.LogLevel.LogLevel_ERROR,
                                       "PyTSon", 0)
                with open(self.ini, 'w') as configfile:
                    self.cfg.write(configfile)
        except:
            from traceback import format_exc
            logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                       "PyTSon", 0)
        # End getValues method +

    def configure(self, qParentWidget):
        try:
            # Start QDialog method +
            if not self.dlg:
                self.dlg = SettingsDialog(self)
            self.dlg.show()
            self.dlg.raise_()
            self.dlg.activateWindow()
            # End QDialog method -
            # Start getValues method +
            d = dict()
            d['api'] = (ValueType.string, "Example String:",
                        self.cfg['general']['example string'], None, 1)
            widgets = getValues(None, self.name + " Settings", d,
                                self.configDialogClosed)
            # End getValues method -
            # Start QInputDialog method +
            result = QInputDialog.getText(
                qParentWidget, self.name + " Settings", "Example String:",
                QLineEdit.Normal, self.cfg['general']['example string'])
            if not result: return
            self.cfg.set('general', 'api', result)
            with open(self.ini, 'w') as configfile:
                self.cfg.write(configfile)
            # End QInputDialog method -
        except:
            from traceback import format_exc
            logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                       "PyTSon", 0)
예제 #30
0
class serverBrowser(ts3plugin):
    shortname = "PS"
    name = "Better Server Browser"
    apiVersion = 21
    requestAutoload = False
    version = "1.0"
    author = "Bluscream"
    description = "A better serverlist provided by PlanetTeamspeak.\n\nCheck out https://r4p3.net/forums/plugins.68/ for more plugins."
    offersConfigure = True
    commandKeyword = ""
    infoTitle = ""
    menuItems = [(ts3defines.PluginMenuType.PLUGIN_MENU_TYPE_GLOBAL, 0,
                  "Browse Servers", "scripts/serverBrowser/gfx/icon.png"),
                 (ts3defines.PluginMenuType.PLUGIN_MENU_TYPE_GLOBAL, 1,
                  "View on PT", "")]
    hotkeys = []
    debug = False
    ini = os.path.join(ts3.getPluginPath(), "pyTSon", "scripts",
                       "serverBrowser", "cfg", "serverBrowser.ini")
    config = configparser.ConfigParser()

    def __init__(self):
        if os.path.isfile(self.ini):
            self.config.read(self.ini)
            #for key, value in self.config["FILTERS"].items():
            #ts3.printMessageToCurrentTab(str(key).title()+": "+str(value))
        else:
            self.config['GENERAL'] = {
                "debug": "False",
                "api": "https://api.planetteamspeak.com/",
                "morerequests": "False",
                "serversperpage": "100"
            }
            self.config['FILTERS'] = {
                "serverNameModifier": "Contains",
                "filterServerName": "",
                "countryBox": "",
                "hideEmpty": "False",
                "hideFull": "False",
                "maxUsers": "False",
                "maxUsersMin": "0",
                "maxUsersMax": "0",
                "maxSlots": "False",
                "maxSlotsMin": "0",
                "maxSlotsMax": "0",
                "filterPassword": "******",
                "filterChannels": "all"
            }
            with open(self.ini, 'w') as configfile:
                self.config.write(configfile)

        ts3.logMessage(
            self.name + " script for pyTSon by " + self.author +
            " loaded from \"" + __file__ + "\".",
            ts3defines.LogLevel.LogLevel_INFO, "Python Script", 0)
        if self.config['GENERAL']['debug'] == "True":
            ts3.printMessageToCurrentTab(
                '[{:%Y-%m-%d %H:%M:%S}]'.format(datetime.now()) +
                " [color=orange]" + self.name +
                "[/color] Plugin for pyTSon by [url=https://github.com/" +
                self.author + "]Bluscream[/url] loaded.")

    def infoData(self, schid, id, atype):
        pass

    def log(self,
            message,
            channel=ts3defines.LogLevel.LogLevel_INFO,
            server=0):
        try:
            ts3.logMessage(message, channel, self.name, server)
            if self.config['GENERAL']['debug'] == "True":
                ts3.printMessageToCurrentTab(
                    '[{:%Y-%m-%d %H:%M:%S}]'.format(datetime.now()) + " " +
                    self.shortname + "> " + message)
                print('[{:%Y-%m-%d %H:%M:%S}]'.format(datetime.now()) + " " +
                      self.shortname + "> (" + str(channel) + ")" + message)
        except:
            _a = None

    def configure(self, qParentWidget):
        d = dict()
        d['debug'] = (ValueType.boolean, "Debug",
                      self.config['GENERAL']['debug'] == "True", None, None)
        d['morerequests'] = (ValueType.boolean, "Fast Connection",
                             self.config['GENERAL']['morerequests'] == "True",
                             None, None)
        d['serversperpage'] = (ValueType.integer, "Servers per page:",
                               int(self.config['GENERAL']['serversperpage']),
                               0, 250)
        d['api'] = (ValueType.string, "API Base URL:",
                    self.config['GENERAL']['api'], None, 1)
        getValues(None, "Server Browser Settings", d, self.configDialogClosed)

    def configDialogClosed(self, r, vals):
        if r == QDialog.Accepted:
            self.config['GENERAL'] = {
                "debug": str(vals['debug']),
                "api": vals['api'],
                "morerequests": str(vals['morerequests']),
                "serversperpage": str(vals['serversperpage'])
            }
            with open(self.ini, 'w') as configfile:
                self.config.write(configfile)

    def onMenuItemEvent(self, schid, atype, menuItemID, selectedItemID):
        if atype == ts3defines.PluginMenuType.PLUGIN_MENU_TYPE_GLOBAL:
            if menuItemID == 0:
                self.dlg = ServersDialog(self)
                self.dlg.show()
                #ts3.printMessageToCurrentTab(str(self.filters))
            elif menuItemID == 1:
                _schid = ts3.getCurrentServerConnectionHandlerID()
                (error, _clid) = ts3.getClientID(_schid)
                (error, _ip) = ts3.getConnectionVariableAsString(
                    _schid, _clid,
                    ts3defines.ConnectionProperties.CONNECTION_SERVER_IP)
                (error, _port) = ts3.getConnectionVariableAsString(
                    _schid, _clid,
                    ts3defines.ConnectionProperties.CONNECTION_SERVER_PORT)
                url = ""
                if _port != "":
                    _url = self.config['GENERAL'][
                        'api'] + "serverlist/result/server/ip/" + _ip + ":" + _port + "/"
                else:
                    _url = self.config['GENERAL'][
                        'api'] + "serverlist/result/server/ip/" + _ip + "/"
                ts3.printMessageToCurrentTab(
                    str("Navigating to \"" + _url + "\""))
                webbrowser.open(_url)
예제 #31
0
class profile(ts3plugin):
    name = "Profile"

    apiVersion = 22
    requestAutoload = False
    version = "1.0"
    author = "Bluscream"
    description = "Share your info\n\nCheck out https://r4p3.net/forums/plugins.68/ for more plugins."
    offersConfigure = True
    commandKeyword = ""
    infoTitle = "[b]" + name + ":[/b]"
    menuItems = []
    hotkeys = []
    ini = os.path.join(ts3.getPluginPath(), "pyTSon", "scripts", "profile",
                       "cfg", "profile.ini")
    config = configparser.ConfigParser()
    META_START = '<profile>'
    META_DIVIDER = '##$#'
    META_COLON = '§$#'
    META_STOP = '</profile>'

    @staticmethod
    def timestamp():
        return '[{:%Y-%m-%d %H:%M:%S}] '.format(datetime.now())

    def __init__(self):
        if os.path.isfile(self.ini):
            self.config.read(self.ini)
        else:
            self.config['GENERAL'] = {"Debug": "False"}
            self.config['PROFILE'] = {
                "Test": "[url=https://google.com]Google[/url]"
            }
            with open(self.ini, 'w') as configfile:
                self.config.write(configfile)

        if self.config['GENERAL']['Debug'] == "True":
            ts3.printMessageToCurrentTab(
                "{0}[color=orange]{1}[/color] Plugin for pyTSon by [url=https://github.com/{2}]{2}[/url] loaded."
                .format(self.timestamp(), self.name, self.author))

    def configure(self, qParentWidget):
        if not self.dlg:
            self.dlg = MainWindow(self)
        self.dlg.show()
        self.dlg.raise_()
        self.dlg.activateWindow()

    def infoData(self, schid, id, atype):
        schid = ts3.getCurrentServerConnectionHandlerID()
        if atype == 2:
            (error, meta) = ts3.getClientVariableAsString(
                schid, id, ts3defines.ClientProperties.CLIENT_META_DATA)
            if error == ts3defines.ERROR_ok and meta != "" and self.META_START in meta and self.META_STOP in meta:
                _tmp = ""
                meta = meta.split(self.META_START)[1]
                meta = meta.split(self.META_STOP)[0]
                meta = meta.split(self.META_DIVIDER)
                for item in meta:
                    item = item.split(self.META_COLON)
                    ts3.printMessageToCurrentTab("item: " + str(item))
                    _tmp += item[0] + ": " + item[1]
                if not _tmp == "":
                    return _tmp.replace("\n", "").replace("\r", "")