Beispiel #1
0
 def loadTemplates(self, reply):
     try:
         data = reply.readAll().data().decode('utf-8')
         # if PluginHost.cfg.getboolean("general", "verbose"):
         json_data = loads(data, object_pairs_hook=OrderedDict)
         if "prefix" in json_data: self.prefix = json_data["prefix"]
         if "suffix" in json_data: self.suffix = json_data["suffix"]
         templates = json_data["templates"]
         for reason, duration in templates.items():
             try:
                 if isinstance(duration, int): continue
                 if duration.isdigit(): templates[reason] = int(duration)
                 elif isinstance(duration, str):
                     if duration.lower() in [
                             "max", "perm", "permanent", "infinite"
                     ]:
                         templates[reason] = 0
                         continue
                     delta = self.parse_time(duration)
                     if not delta:
                         print("Can't load", reason, duration)
                         continue
                     templates[reason] = int(delta.total_seconds())
             except:
                 ts3lib.logMessage(format_exc(),
                                   ts3defines.LogLevel.LogLevel_ERROR,
                                   "pyTSon", 0)
         self.templates = templates
         if PluginHost.cfg.getboolean("general", "verbose"):
             print(self.name, "> Downloaded ban templates:", self.templates)
     except:
         ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                           "pyTSon", 0)
Beispiel #2
0
 def validate(self, elem, pattern, text, reason=None):
     try:
         actions = elem.actions()
         if not text:
             elem.setToolTip("")
             if self.icon_warning:
                 if len(actions): elem.removeAction(actions[0])
             else: elem.setStyleSheet("")
         valid = re.match(pattern, text)
         if not valid:
             if reason: elem.setToolTip(reason)
             else:
                 elem.setToolTip("This {name} seems to be invalid!".format(
                     name=elem.parentWidget().title))
             if self.icon_warning:
                 if not len(actions):
                     elem.addAction(self.icon_warning,
                                    QLineEdit.LeadingPosition)
             else:
                 elem.setStyleSheet("background-color:#5C4601")
         else:
             elem.setToolTip("")
             if self.icon_warning:
                 if len(actions): elem.removeAction(actions[0])
             else: elem.setStyleSheet("")
     except:
         ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                           "pyTSon", 0)
Beispiel #3
0
 def on_btn_apply_clicked(self):
     try:
         self.this.cfg.set('general', 'debug',
                           str(self.chk_debug.isChecked()))
         if self.chk_whitelist.isChecked():
             self.this.cfg.set('general', 'whitelist', 'True')
         else:
             self.this.cfg.set('general', 'whitelist', 'False')
         if self.chk_kick.isChecked():
             self.this.cfg.set('main', 'kickonly', 'True')
         else:
             self.this.cfg.set('main', 'kickonly', 'False')
         if self.chk_kick_2.isChecked():
             self.this.cfg.set('failover', 'kickonly', 'True')
         else:
             self.this.cfg.set('failover', 'kickonly', 'False')
         self.this.cfg.set('main', 'bantime', str(self.bantime.value))
         self.this.cfg.set('failover', 'bantime', str(self.bantime_2.value))
         self.this.cfg.set('api', 'main', self.api_main.text)
         self.this.cfg.set('api', 'fallback', self.api_fallback.text)
         self.this.cfg.set('failover', 'enabled',
                           str(self.chk_failover.isChecked()))
         for index in range(self.lst_events.count):
             item = self.lst_events.item(index)
             for event in self.this.cfg['events']:
                 if item.text().lower() == event:
                     self.this.cfg.set('events', item.text(),
                                       str(item.checkState() == Qt.Checked))
         with open(self.this.ini, 'w') as configfile:
             self.this.cfg.write(configfile)
         self.close()
     except:
         ts3.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                        "PyTSon", 0)
Beispiel #4
0
 def __init__(self, script, schid, clid, uid, name, ip, parent=None):
     try:
         super(QDialog, self).__init__(parent)
         setupUi(self, "%s/ban.ui"%script.path)
         self.setAttribute(Qt.WA_DeleteOnClose)
         self.cfg = script.cfg
         self.ini = script.ini
         self.schid = schid
         self.templates = script.templates
         self.whitelist = script.whitelist
         self.name = script.name
         if script.cfg.getboolean("last", "expanded"):
             self.disableReasons(True)
         height = script.cfg.get("last", "height")
         if height: self.resize(self.width, int(height))
         else: self.disableReasons()
         alt = script.cfg.getboolean("last", "alternate")
         if alt: self.chk_alternate.setChecked(True)
         dblclick = script.cfg.getboolean("last", "ban on doubleclick")
         if dblclick: self.chk_doubleclick.setChecked(True)
         for reason in script.templates:
             self.lst_reasons.addItem(reason)
             self.box_reason.addItem(reason)
         self.box_reason.setEditText(script.cfg.get("last", "reason")) # setItemText(0, )
         self.setup(script, schid, clid, uid, name, ip)
     except: ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)
Beispiel #5
0
 def on_btn_ban_clicked(self):
     try:
         ip = self.txt_ip.text if self.grp_ip.isChecked() else ""
         name = self.txt_name.text if self.grp_name.isChecked() else ""
         uid = self.txt_uid.text if self.grp_uid.isChecked() else ""
         reason = self.box_reason.currentText
         if reason[0].isdigit():
             reason = "§" + reason
         duration = self.int_duration.value
         if self.moveBeforeBan: ts3lib.requestClientMove(self.schid, self.clid, 26, "")
         if ip:
             check = True
             if len(self.whitelist) < 1: check = confirm("Empty IP Whitelist!", "The IP whitelist is empty! Are you sure you want to ban \"{}\"?\n\nMake sure your whitelist URL\n{}\nis working!".format(ip, self.cfg.get("general", "whitelist")))
             if ip in self.whitelist: ts3lib.printMessageToCurrentTab("{}: [color=red]Not banning whitelisted IP [b]{}".format(self.name, ip))
             elif check: ts3lib.banadd(self.schid, ip, "", "", duration, reason)
         if name: ts3lib.banadd(self.schid, "", name, "", duration, reason)
         if uid: ts3lib.banadd(self.schid, "", "", uid, duration, reason)
         # msgBox("schid: %s\nip: %s\nname: %s\nuid: %s\nduration: %s\nreason: %s"%(self.schid, ip, name, uid, duration, reason))
         self.cfg["last"] = {
             "ip": str(self.grp_ip.isChecked()),
             "name": str(self.grp_name.isChecked()),
             "uid": str(self.grp_uid.isChecked()),
             "reason": reason,
             "duration": str(duration),
             "expanded": str(self.lst_reasons.isVisible()),
             "height": str(self.height),
             "alternate": str(self.chk_alternate.isChecked()),
             "ban on doubleclick": str(self.chk_doubleclick.isChecked()),
         }
         if not self.chk_keep.isChecked():
             self.close()
     except: ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)
Beispiel #6
0
 def getLinkInfo(self, urls):
     domains = "/".join(urls)
     url = "http://api.mywot.com/0.4/public_link_json2?hosts=%s/&key=%s" % (domains,self.wot_api_key)
     ts3lib.logMessage('Requesting %s'%url, ts3defines.LogLevel.LogLevel_ERROR, "PyTSon Linkinfo Script", 0)
     self.nwm = QNetworkAccessManager()
     self.nwm.connect("finished(QNetworkReply*)", self.onWOTReply)
     self.nwm.get(QNetworkRequest(QUrl(url)))
Beispiel #7
0
 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")
Beispiel #8
0
 def processCommand(self, schid, fullcmd):
     try:
         cmd = fullcmd.split(' ', 1)
         mode = cmd[0].lower()
         _cmd = cmd[1].split(' ', 1)
         targetmode = _cmd[0].lower()
         command = _cmd[1]
         target = []
         if targetmode in ["chan", "channel", "0"]:
             targetmode = ts3defines.PluginTargetMode.PluginCommandTarget_CURRENT_CHANNEL
         elif targetmode in ["serv", "server", "1"]:
             targetmode = ts3defines.PluginTargetMode.PluginCommandTarget_SERVER
         elif targetmode in ["cli", "client", "2"]:
             targetmode = ts3defines.PluginTargetMode.PluginCommandTarget_CLIENT
             _cmd = command[1].split(' ', 1)
             target = [int(_cmd[0])]
             command = _cmd[1]
         elif targetmode in ["chansub", "channelsubscribed", "3"]:
             targetmode = ts3defines.PluginTargetMode.PluginCommandTarget_CURRENT_CHANNEL_SUBSCRIBED_CLIENTS
         if mode in ["raw", "r", "true", "1"]:
             _ts3lib.sendPluginCommand(schid, command, targetmode, target)
         else:
             ts3lib.sendPluginCommand(schid, command, targetmode, target)
         return True
     except:
         ts3lib.printMessageToCurrentTab(
             "Syntax: [b]/py {} <raw> <channel,server,channelsubscribed,client <clid>> <cmd>"
             .format(self.commandKeyword))
         ts3lib.logMessage(
             "Error while processing \"{}\"\n{}".format(
                 fullcmd, format_exc()),
             ts3defines.LogLevel.LogLevel_WARNING, self.name, schid)
Beispiel #9
0
    def onTextMessageEvent(self, schid, targetMode, toID, fromID, fromName,
                           fromUniqueIdentifier, message, ffIgnored):
        try:
            messageL = message.lower()

            bookmarkFind = messageL.find(
                "addbookmark=")  # ts3server://localhost?addbookmark=
            if (bookmarkFind == -1):
                return

            closedFind = messageL.find("]")
            if (closedFind == -1):
                return

            tagFind = messageL.find("<")
            if (tagFind == -1):
                return

            if (tagFind > closedFind or tagFind < bookmarkFind):
                return

            ts3.printMessageToCurrentTab(
                "[color=red]{0} send a faulty link[/color]".format(fromName))

            return True  # ignore msg
        except:
            from traceback import format_exc
            ts3.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                           "PyTSon", 0)
Beispiel #10
0
 def on_navigate(self, page=1, direction=0):
     try:
         if self.cooldown_page:
             self.status.setText("You have to wait " +
                                 str(self.cooldown_time_page / 1000) +
                                 " second(s) before switching pages!")
             palette = QPalette()
             palette.setColor(QPalette.Foreground, Qt.red)
             self.status.setPalette(palette)
             return
         if direction == 2:
             self.page += page
         elif direction == 1:
             self.page -= page
         else:
             self.page = page
         self.listServers()
         if not self.cooldown:
             self.cooldown_page = True
             self.previous.setEnabled(False)
             self.next.setEnabled(False)
             self.first.setEnabled(False)
             self.last.setEnabled(False)
             QTimer.singleShot(self.cooldown_time_page,
                               self.disable_cooldown_page)
     except:
         ts3.logMessage(traceback.format_exc(),
                        ts3defines.LogLevel.LogLevel_ERROR, "PyTSon", 0)
Beispiel #11
0
    def infoData(self, schid, clid, atype): # https://github.com/teamspeak-plugins/now_playing/blob/master/now_playing/nowplaying_plugin.c#L667
        if atype == 2 and self.cfg.getboolean("general", "infodata"):
            i = []
            addons = self.parseMeta(schid, clid)
            try:
                for addon in addons:
                    try:
                        string = "%s"%addon.text
                        # string += " v%s"%addon.attrib["version"]
                        string += " by %s"%addon.attrib["author"]
                        i.append(string)
                    except:
                        if PluginHost.cfg.getboolean("general", "verbose"): from traceback import format_exc;ts3.logMessage("Error listing {0}: {1}".format(addon.text, format_exc()), ts3defines.LogLevel.LogLevel_ERROR, self.name, schid)
                        pass
                pytsons = [element for element in addons.iter() if element.text == 'pyTSon']
                # xm = xml.fromstring('<element attribute="value">text<subelement subattribute="subvalue">subtext</subelement></element>')
                for pytson in pytsons:
                    scripts = pytson.findall("script")
                    i.append("[u]pyTSon[/u]:")
                    for script in scripts:
                        try: i.append("{name} v{version} by {author}".format(name=script.text,version=script.attrib["version"],author=script.attrib["author"]))
                        except:from traceback import format_exc;ts3.logMessage("Error parsing meta %s:\n%s"%(script.text,format_exc()), ts3defines.LogLevel.LogLevel_ERROR, "{c}.{f}".format(c=self.__class__,f=__name__), schid);continue

                return i
            except: from traceback import format_exc;ts3.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0);pass
Beispiel #12
0
 def __init__(self, purgeContacts, filter, txt, date, parent=None):
     try:
         super(QDialog, self).__init__(parent)
         setupUi(self, path.join(purgeContacts.scriptpath, "preview.ui"))
         self.setAttribute(Qt.WA_DeleteOnClose)
         db = ts3client.Config()
         q = db.query("SELECT * FROM contacts")
         while q.next():
             contact = q.value("value").split('\n')
             """
             if line.startswith('Friend='):
                 status = int(line[-1])
                 if status == ContactStatus.FRIEND: buddies += 1
                 elif status == ContactStatus.BLOCKED: blocked += 1
                 elif status == ContactStatus.NEUTRAL: neutral += 1
                 else: unknown += 1
             elif line.lower().startswith('nickname=w/'):
                 female += 1
             elif line.lower().startswith('nickname=m/'):
                 male += 1
             """
         del db
         # self.setWindowTitle(self.windowTitle().format()) # TODO
     except:
         ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                           "pyTSon", 0)
Beispiel #13
0
 def delActive(self):
     try:
         row = self.lst_active.currentRow
         self.lst_active.takeItem(row)
         if self.chk_autoApply.checkState() == Qt.Checked:
             self.updateBadges()
     except: ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)
Beispiel #14
0
 def tick(self):
     try:
         self.retcode = ts3lib.createReturnCode()
         if self.mode == 0:
             if self.pwc >= len(self.pws):
                 self.timer.stop()
                 (err, name) = ts3lib.getChannelVariable(
                     self.schid, self.cid, ChannelProperties.CHANNEL_NAME)
                 msgBox(
                     "Password for channel \"{0}\" was not found :(\n\nTried {1} passwords."
                     .format(name, self.pwc + 1))
                 self.cracking = False
                 return
             pw = self.pws[self.pwc]
         elif self.mode == 1:
             pw = str(self.pwc)
         err = ts3lib.verifyChannelPassword(self.schid, self.cid, pw,
                                            self.retcode)
         if err != ERROR_ok:
             (er, status) = ts3lib.getErrorMessage(err)
             print(
                 'ERROR {0} ({1}) while trying password \"{2}\" for channel #{3} on server #{4}'
                 .format(status, err, pw, self.cid, self.schid))
         # else: print('[{0}] Trying password \"{1}\" for channel #{2} on server #{3}'.format(self.pwc, pw, self.cid, self.schid))
         if not self.flooding: self.pwc += self.step
     except:
         from traceback import format_exc
         ts3lib.logMessage(format_exc(), LogLevel.LogLevel_ERROR, "pyTSon",
                           0)
Beispiel #15
0
    def __init__(cls, name, bases, attrs):
        super(PluginMount, cls).__init__(name, bases, attrs)
        if not hasattr(PluginHost, 'plugins'):
            PluginHost.plugins = {}
            PluginHost.active = {}
        else:
            for a in ['requestAutoload', 'name', 'version', 'apiVersion',
                      'author', 'description', 'offersConfigure',
                      'commandKeyword', 'infoTitle', 'menuItems', 'hotkeys']:
                if not hasattr(cls, a):
                    msg = cls._tr("Plugin {name} not loaded, missing required "
                                  "attribute {attrib}").format(name=name,
                                                               attrib=a)
                    err = ts3lib.logMessage(msg,
                                            ts3defines.LogLevel.LogLevel_ERROR,
                                            "pyTSon.PluginMount.init", 0)
                    if err != ts3defines.ERROR_ok:
                        print(msg)

                    return

            if cls.name not in PluginHost.plugins:
                PluginHost.plugins[cls.name] = cls
            else:
                msg = cls._tr("Error loading python plugin {name}, already "
                              "registered or a plugin with that name already "
                              "exists").format(name=cls.name)
                err = ts3lib.logMessage(msg,
                                        ts3defines.LogLevel.LogLevel_ERROR,
                                        "pyTSon.PluginMount.init", 0)
                if err != ts3defines.ERROR_ok:
                    print(msg)
Beispiel #16
0
 def addActive(self, ext=False):
     try:
         item = self.lst_available_ext.currentItem() if ext else self.lst_available.currentItem()
         self.lst_active.addItem(self.badgeItem(item.data(Qt.UserRole), False, True if ext else False))
         if self.chk_autoApply.checkState() == Qt.Checked:
             self.updateBadges()
     except: ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)
Beispiel #17
0
 def on_btn_apply_clicked(self):
     try:
         self.cfg.set('general', 'enabled', str(self.chk_enabled.isChecked()))
         self.cfg.set('general', 'debug', str(self.chk_debug.isChecked()))
         self.cfg.set('general', 'unknowncmd', str(self.chk_unknowncmd.isChecked()))
         self.cfg.set('general', 'disabledcmd', str(self.chk_disabledcmd.isChecked()))
         self.cfg.set('general', 'customprefix', str(self.grp_prefix.isChecked()))
         self.cfg.set('general', 'prefix', self.txt_prefix.text)
         with open(self.ini, 'w') as configfile:
             self.cfg.write(configfile)
         i = 0
         while i < self.tbl_commands.rowCount:
             try:
                 if self.cfg.getboolean("general", "debug"): ts3lib.printMessageToCurrentTab("{0}".format(self.tbl_commands.item(i, 0)))
                 if not self.tbl_commands.item(i, 0).text() in self.cmd.sections(): self.cmd.add_section(i)
                 self.cmd.set(self.tbl_commands.item(i, 0).text(), "function", self.tbl_commands.item(i, 1).text())
                 self.cmd.set(self.tbl_commands.item(i, 0).text(), "enabled", str(self.tbl_commands.item(i, 0).checkState() == Qt.Checked))
             except:
                 from traceback import format_exc;ts3lib.logMessage("Could not add row {0} to commands.ini\n{1}".format(i, format_exc()), ts3defines.LogLevel.LogLevel_INFO, "pyTSon Chat Bot", 0)
             i += 1
         with open(self.cmdini, 'w') as configfile:
             self.cmd.write(configfile)
         self.loadCommands();
     except:
         from traceback import format_exc;ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)
Beispiel #18
0
def urlResponse(reply):
    try:
        from PythonQt.QtNetwork import QNetworkReply
        if reply.error() == QNetworkReply.NoError:
            print("Error: %s (%s)" % (reply.error(), reply.errorString()))
            print("Content-Type: %s" %
                  reply.header(QNetworkRequest.ContentTypeHeader))
            print("<< reply.readAll().data().decode('utf-8') >>")
            print("%s" % reply.readAll().data().decode('utf-8'))
            print("<< reply.readAll().data() >>")
            print("%s" % reply.readAll().data())
            print("<< reply.readAll() >>")
            print("%s" % reply.readAll())
            return reply
        else:
            err = logMessage("Error checking for update: %s" % reply.error(),
                             ts3defines.LogLevel.LogLevel_ERROR,
                             "pyTSon.PluginHost.updateCheckFinished", 0)
            if err != ts3defines.ERROR_ok:
                print("Error checking for update: %s" % reply.error())
        urlrequest.delete()
    except:
        from traceback import format_exc
        try:
            ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                              "PyTSon::autorun", 0)
        except:
            print("Error in autorun: " + format_exc())
Beispiel #19
0
 def __init__(self, addons, name, cfg, parent=None):
     try:
         super(QWidget, self).__init__(parent)
         setupUi(
             self,
             path.join(pytson.getPluginPath(), "scripts", "addonList",
                       "addons.ui"))
         self.cfg = cfg
         self.setAttribute(Qt.WA_DeleteOnClose)
         self.setWindowTitle("{0}'s Addons".format(name))
         self.txt_description.setVisible(False)
         self.tbl_addons.horizontalHeader().setSectionResizeMode(
             0, QHeaderView.Stretch)
         self.tbl_addons.horizontalHeader().setSectionResizeMode(
             2, QHeaderView.Stretch)
         self.setupList(addons.getchildren())
         self.resize(1000, 600)
         self.adddons = addons
     except:
         try:
             from traceback import format_exc
             ts3.logMessage("addonList: " + format_exc(),
                            ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)
         except:
             try:
                 from traceback import format_exc
                 print("addonList: " + format_exc())
             except:
                 print("addonList: Unknown Error")
Beispiel #20
0
 def __init__(self):
     try:
         import unidecode
     except ImportError:
         PluginInstaller().installPackages(['unidecode'])
     try:
         from discoIPC import ipc
     except ImportError:
         PluginInstaller().installPackages(['discoIPC'])
         from discoIPC import ipc
     self.discord = ipc.DiscordIPC(
         "504997049226362891")  # 450824928841957386
     try:
         self.discord.connect()
     except:
         ts3lib.logMessage("Discord not running!",
                           ts3defines.LogLevel.LogLevel_WARNING,
                           "pyTSon Discord Rich Presence", 0)
     self.timer.timeout.connect(self.tick)
     self.timer.setTimerType(2)
     schid = ts3lib.getCurrentServerConnectionHandlerID()
     self.onTabChangedEvent(schid)
     self.timer.start(1000)
     """
     (err, status) = ts3lib.getConnectionStatus(schid)
     if status == ts3defines.ConnectStatus.STATUS_CONNECTION_ESTABLISHED:
         self.updateServer(schid); self.updateChannel(schid); self.updateVoice(schid);self.updateClient(schid)
     """
     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))
Beispiel #21
0
 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())
Beispiel #22
0
 def onServerUpdatedEvent(self, schid):
     (err, cmdblock) = ts3lib.getServerVariable(schid, VirtualServerPropertiesRare.VIRTUALSERVER_ANTIFLOOD_POINTS_NEEDED_COMMAND_BLOCK)
     (err, ipblock) = ts3lib.getServerVariable(schid, VirtualServerPropertiesRare.VIRTUALSERVER_ANTIFLOOD_POINTS_NEEDED_IP_BLOCK)
     (err, afreduce) = ts3lib.getServerVariable(schid, VirtualServerPropertiesRare.VIRTUALSERVER_ANTIFLOOD_POINTS_TICK_REDUCE)
     ts3lib.logMessage("schid = {0} | err = {1} | afreduce = {2} | cmdblock = {3} | ipblock = {4} | verify_antiflood_points = {5}".format(schid, err, afreduce, cmdblock, ipblock, self.verify_antiflood_points), LogLevel.LogLevel_INFO, "pyTSon", 0)
     self.interval = round(1000/((afreduce/self.verify_antiflood_points)))
     ts3lib.logMessage("Set interval to {0}".format(self.interval), LogLevel.LogLevel_INFO, "pyTSon", 0)
Beispiel #23
0
 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()
Beispiel #24
0
 def reconnect(self, schid=None):
     try:
         schid = schid if schid else self.schid
         args = [
             ts3defines.PluginConnectTab.
             PLUGIN_CONNECT_TAB_NEW_IF_CURRENT_CONNECTED,  # connectTab: int,
             self.tabs[schid]["name"],  # serverLabel: Union[str, unicode],
             self.tabs[schid]
             ["address"],  # serverAddress: Union[str, unicode],
             self.tabs[schid]["pw"],  # serverPassword: Union[str, unicode],
             self.tabs[schid]["nick"],  # nickname: Union[str, unicode],
             self.tabs[schid]["cpath"],  # channel: Union[str, unicode],
             self.tabs[schid]
             ["cpw"],  # channelPassword: Union[str, unicode]
             "",  # captureProfile: Union[str, unicode],
             "",  # playbackProfile: Union[str, unicode]
             "",  # hotkeyProfile: Union[str, unicode],
             "Default Sound Pack (Female)",  # soundPack
             self.tabs[schid]["uid"],  # userIdentity: Union[str, unicode],
             self.tabs[schid]["token"],  # oneTimeKey: Union[str, unicode],
             self.tabs[schid][
                 "nick_phonetic"]  # phoneticName: Union[str, unicode]
         ]
         print("ts3lib.guiConnect({})".format("\", \"".join(
             str(x) for x in args)))
         ts3lib.guiConnect(args[0], args[1], args[2], args[3], args[4],
                           args[5], args[6], args[7], args[8], args[9],
                           args[10], args[11], args[12], args[13])
         self.schid = 0
     except:
         from traceback import format_exc
         ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                           "pyTSon", 0)
Beispiel #25
0
 def restoreTabs(self):
     try:
         err, schids = ts3lib.getServerConnectionHandlerList()
         if err != ERROR_ok: return
         if len(schids) > 1: return
         for schid in schids:
             (err, status) = ts3lib.getConnectionStatus(schid)
             if err != ERROR_ok: return
             if status != ConnectStatus.STATUS_DISCONNECTED: return
         self._tabs = {}
         self._timers = []
         with open(self.backup_file) as f:
             self._tabs = load(f)
         i = 0
         self._delay = self.delay
         for tab in self._tabs:
             i += 1
             # if self._tabs[tab]["status"] == ConnectStatus.STATUS_CONNECTION_ESTABLISHED:
             timer = QTimer()
             self._timers.append(timer)
             timer.singleShot(self._delay, self.restoreTab)
             # self.restoreTab(tab)
             self._delay += self.increase
     except:
         ts3lib.logMessage(format_exc(), LogLevel.LogLevel_ERROR, "pyTSon",
                           0)
Beispiel #26
0
 def onClientBanFromServerEvent(self, serverConnectionHandlerID, clientID, oldChannelID, newChannelID, visibility, kickerID, kickerName, kickerUniqueIdentifier, time, kickMessage):
     try:
         ts3lib.playWaveFile(serverConnectionHandlerID, path.join(self.soundPath, "ahfuck.wav"))
         ts3lib.printMessageToCurrentTab("f**k")
         if self.cfg['antiserverban']['enabled'] != 'False' and self.antiServerBanStatus != False:
             if time != 0 and time < self.maxSleepTime:
                 tabID = int(self.cfg['data']['tabID'])
                 ip = self.cfg['data']['ip']
                 port = self.cfg['data']['port']
                 #serverPw = self.cfg['general']['serverpw']
                 serverPw = self.currentServerPW
                 nickname = self.cfg['data']['nickname']
                 channelList = []
                 channelPw = self.cfg['general']['channelpw']
                 identity = self.cfg['general']['identity']
                 address = ip + ":" + port
                 if time > 30:
                     time = time + 1
                 self.sleep(time)
                 (error, schid) = ts3lib.guiConnect(tabID, "Server", address, serverPw, nickname, "", channelPw, "default", "default", "default", "default", identity, "", "")
                 if self.cfg['antiserverban']['rejoinchannel'] != "False":
                     self.rejoinChannel = True
                     self.oldChannelID = oldChannelID
             self.backup(schid)
             #identity = self.cfg['data']['identityPrefix'] + self.cfg['data']['currentID']
             #(error, schid) = ts3lib.guiConnect(tabID, "Server", address, serverPw, nickname, "", channelPw, "", "", "", "default", identity, "", "")
             #self.cfg['data']['currentID'] = self.cfg['data']['currentID'] + 1
     except: from traceback import format_exc;ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "PyTSon", 0)
Beispiel #27
0
    def onCountryListReply(self, reply):
        try:
            _api = self.serverBrowser.config['GENERAL']['api']
            _reply = reply.readAll()
            countries = json.loads(_reply.data().decode('utf-8'))["result"]["data"]
            ts3.printMessageToCurrentTab("%s"%countries)
            _reason = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
            self.status.setText("Response from \"{0}\": {1}: {2}".format(_api, _reason, reply.attribute(QNetworkRequest.HttpReasonPhraseAttribute)))
            palette = QPalette()
            if _reason == 200:
                palette.setColor(QPalette.Foreground,Qt.darkGreen)
                self.countryBox.clear()
            else:
                palette.setColor(QPalette.Foreground,Qt.red)
            self.status.setPalette(palette)
            y= sum(x[2] for x in countries)
            #y = 0
            #for x in countries:
            #   y = y + x[2]
            #ts3.printMessageToCurrentTab(str(countries))
            if "-" in [h[0] for h in countries]:
                countries = countries[0:1]+sorted(countries[1:],key=lambda x: x[1])
            else:
                countries = sorted(countries,key=lambda x: x[1])
            self.countries = [['ALL', 'All', y]]+countries
            #if self.serverBrowser.config['GENERAL']['morerequests'] == "True":
                #self.countryBox.addItems([x[1]+" ("+str(x[2])+")" for x in self.countries])
            #else:
            self.countryBox.addItems([x[1] for x in self.countries])

            #__countries = __countries.__add__([['ALL', 'All', 0]])
        except:
            ts3.logMessage(traceback.format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)
Beispiel #28
0
 def __init__(self):
     if path.isfile(self.ini):
         self.cfg.read(self.ini)
     else:
         self.cfg['general'] = { "cfgversion": "1", "debug": "False", "enabled": "True", "channelpw": "123", "serverpw": "123", "anticrash": "True" , "identity": "default"}
         self.cfg['antimove'] = { "enabled": "True", "delay": "0", "defaultstatus": "True", "message": "False"}
         self.cfg['antichannelkick'] = { "enabled": "True", "delay": "0", "defaultstatus": "True"}
         self.cfg['antichannelban'] = { "enabled": "True", "delay": "0"}
         self.cfg['antiserverkick'] = { "enabled": "True", "delay": "0", "defaultstatus": "True", "rejoinchannel": "True"}
         self.cfg['antiserverban'] = { "enabled": "True", "delay": "0", "defaultstatus": "True", "rejoinchannel": "True", "maxsleeptime": "300"}
         self.cfg['antichanneldelete'] = { "enabled": "True", "delay": "0"}
         self.cfg['data'] = { "ip": "127.0.0.1", "port": "9987", "channelid": "0", "channelname": "Default Channel", "nickname": "TeamspeakUser", "phoneticnick": "", "metaData": "", "tabID": "0", "identityPrefix": "Neue Identität_", "currentID": "1"}
         self.cfg['passwords'] = { "passwords": "123,1234"}
         with open(self.ini, 'w') as configfile:
             self.cfg.write(configfile)
     ts3lib.logMessage(self.name + " script for pyTSon by " + self.author + " loaded from \""+__file__+"\".", ts3defines.LogLevel.LogLevel_INFO, "Python Script", 0)
     self.antiMoveStatus = self.cfg['antimove']['defaultstatus']
     self.antiChannelKickStatus = self.cfg['antichannelkick']['defaultstatus']
     self.antiServerKickStatus = self.cfg['antiserverkick']['defaultstatus']
     self.antiServerBanStatus = self.cfg['antiserverban']['defaultstatus']
     self.rejoinChannel = self.cfg['antiserverban']['rejoinchannel']
     self.passwordList = self.cfg['passwords']['passwords'].split(',')
     self.maxSleepTime = int(self.cfg['antiserverban']['maxsleeptime'])
     #ts3lib.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 + "]" + self.author + "[/url] loaded.")
     schid = ts3lib.getCurrentServerConnectionHandlerID()
     if schid != 0: self.backup(schid)
     ts3lib.printMessageToCurrentTab("[{:%Y-%m-%d %H:%M:%S}]".format(datetime.now()) + " Connected to [color=red]" + self.cfg['data']['ip'] + ":" + self.cfg['data']['port'] + "[/color] as [color=blue]" + self.cfg['data']['nickname'] + "[/color] on [color=green]Tab " + self.cfg['data']['tabID'] + "[/color]")
Beispiel #29
0
 def onClientMoveEvent(self, schid, clientID, oldChannelID, newChannelID,
                       visibility, moveMessage):
     if not self.toggle: return
     try:
         (error, ownid) = ts3lib.getClientID(schid)
         if ownid == clientID:
             (error, ntp) = ts3lib.getChannelVariableAsInt(
                 schid, newChannelID,
                 ts3defines.ChannelPropertiesRare.CHANNEL_NEEDED_TALK_POWER)
             if self.debug:
                 ts3lib.printMessageToCurrentTab(
                     'error: {0} | ntp: {1}'.format(error, ntp))
             if ntp < 1: return
             (error, tp) = ts3lib.getClientVariableAsInt(
                 schid, ownid,
                 ts3defines.ClientPropertiesRare.CLIENT_IS_TALKER)
             if self.debug:
                 ts3lib.printMessageToCurrentTab(
                     'error: {0} | tp: {1}'.format(error, tp))
             if tp: return
             self.nwmc = QNetworkAccessManager()
             self.nwmc.connect("finished(QNetworkReply*)", self.jokeReply)
             self.schid = schid
             self.nwmc.get(
                 QNetworkRequest(
                     QUrl("http://tambal.azurewebsites.net/joke/random")))
     except:
         from traceback import format_exc
         ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                           "pyTSon", 0)
Beispiel #30
0
 def configure(self, qParentWidget):
     try:
         d = dict()
         d['debug'] = (ValueType.boolean, "Debug",
                       self.cfg['general']['debug'] == "True", None, None)
         d['enabled'] = (ValueType.boolean, "Broadcast own changes",
                         self.cfg['general']['enabled'] == "True", None,
                         None)
         d['pw'] = (ValueType.boolean, "Broadcast server passwords",
                    self.cfg['general']['pw'] == "True", None, None)
         d['channel'] = (ValueType.boolean, "Broadcast new channel",
                         self.cfg['general']['channel'] == "True", None,
                         None)
         d['channelpw'] = (ValueType.boolean, "Broadcast channel pw",
                           self.cfg['general']['channelpw'] == "True", None,
                           None)
         d['status'] = (ValueType.string, "AFK status text:",
                        self.cfg['general']['status'], None, 1)
         getValues(None, "{} Settings".format(self.name), d,
                   self.configDialogClosed)
     except:
         from traceback import format_exc
         try:
             ts3.logMessage(format_exc(),
                            ts3defines.LogLevel.LogLevel_ERROR,
                            "PyTSon::" + self.name, 0)
         except:
             print("Error in " + self.name + ".configure: " + format_exc())
Beispiel #31
0
 def setupList(self):
     try:
         self.chk_overwolf.setChecked(True if self.cfg.getboolean('general', 'overwolf') else False)
         self.lst_available.clear()
         for badge in self.badges:
             self.lst_available.addItem(self.badgeItem(badge))
         self.grp_available.setTitle("{} Available (Internal)".format(len(self.badges)))
         self.lst_available_ext.clear()
         for badge in self.extbadges:
             self.lst_available_ext.addItem(self.badgeItem(badge, False, True))
         self.grp_available_ext.setTitle("{} Available (External)".format(len(self.extbadges)))
         badges = self.cfg.get('general', 'badges').split(",")
         if len(badges) < 1: return
         self.lst_active.clear()
         i = 0
         for badge in badges:
             if not badge: return
             if i < 3: self.updatePreview(badge, i)
             i += 1
             if badge in self.badges:
                 self.lst_active.addItem(self.badgeItem(badge))
             elif badge in self.extbadges:
                 self.lst_active.addItem(self.badgeItem(badge, False, True))
         self.grp_active.setTitle("{} Active".format(self.lst_active.count))
     except: ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)
Beispiel #32
0
def _errprint(msg, errcode, aid, secid=None):
    if secid:
        err = ts3lib.logMessage("%s (%s): %s" % (msg, secid, errcode),
                                ts3defines.LogLevel.LogLevel_ERROR,
                                "pyTSon.ts3widgets", aid)
    else:
        err = ts3lib.logMessage("%s: %s" % (msg, errcode),
                                ts3defines.LogLevel.LogLevel_ERROR,
                                "pyTSon.ts3widgets", aid)

    if err != ts3defines.ERROR_ok:
        if secid:
            print("%s (%s, %s): %s" % (msg, aid, secid, errcode))
        else:
            print("%s (%s): %s" % (msg, aid, errcode))
Beispiel #33
0
def logprint(msg, loglevel, channel):
    err = ts3lib.logMessage(msg, loglevel, channel, 0)
    if err != ts3defines.ERROR_ok:
        print(msg)
Beispiel #34
0
def ts3print(msg, level, channel, aid):
    err = ts3lib.logMessage(msg, level, channel, aid)
    if err != ts3defines.ERROR_ok:
        print(msg)