Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import ts3
- from pymongo import MongoClient
- import time
- import configparser
- ## Variables ##
- # TS3 Query
- # type: string
- # desc: Server Adress
- _query_server = "127.0.0.1"
- # type: int
- # desc: Query Port
- _query_port =
- # type: int
- # desc: Server Port
- _query_server_port =
- # type: string
- # desc: TS3 Query Username
- _query_username = ""
- # type: string
- # desc: TS3 Query Password
- _query_password = ""
- # type: bool
- # desc: is Config loaded
- _query_configLoaded = False
- # MongoDB
- # type: string
- # desc: MongoDB URL
- # default: 'mongodb://localhost:27017'
- _mongoDB_URL = "mongodb://localhost:27017"
- _mongoDB_pass = "coin"
- _mongoDB_user = "bot"
- # Ranks
- # type: List of list of int
- # desc: Contains the Rankdata, every rank is a list, wich are in the list
- _rank_list = []
- _point_mul = 1
- _user_channel = 42
- _Points_channel = 43
- _monthly_Points_channel = 44
- _refreshed_channel = 45
- ## Funcionts ##
- # Loading
- # name: loadQueryConfig
- # desc: loads the ports, address and userdata for the Query
- def loadQueryConfig():
- config = configparser.ConfigParser()
- config.read("/opt/coinsystem/config.cfg")
- global _query_server
- global _query_port
- global _query_username
- global _query_password
- global _query_configLoaded
- global _query_server_port
- global _mongoDB_pass
- global _mongoDB_URL
- global _mongoDB_user
- _query_server = config.get("SERVER", "ip")
- _query_port = config.getint("SERVER", "port")
- _query_server_port = config.getint("SERVER", "regular_port")
- _query_username = config.get("SERVER", "username")
- _query_password = config.get("SERVER", "password")
- config = configparser.ConfigParser()
- config.read("/opt/coinsystem/mongo.cfg")
- _mongoDB_URL = config.get("SERVER", "url")
- _mongoDB_user = config.get("SERVER", "username")
- _mongoDB_pass = config.get("SERVER", "password")
- _query_configLoaded = True
- # name: loadRanks
- # desc: loads the ranks into the list
- def loadRanks():
- global _rank_list
- # open the ranks config and read every line
- with open("/opt/coinsystem/ranks.dat") as ranks:
- lines = ranks.readlines()
- for line in lines:
- # if not empty or comment
- if line != "\n" and "//" not in line:
- values = line.split(" ")
- _rank_list.append(
- [int(values[0]), int(values[1]), int(values[2])])
- # Query Functions
- # name: getQueryConnection
- # desc: returns a Query Connection and sets Displayname.
- # if not already loaded it also load the cofnig settings
- def getQueryConnection():
- if not _query_configLoaded:
- loadQueryConfig()
- server = ts3.query.TS3Connection(_query_server, _query_port)
- server.login(client_login_name=_query_username,
- client_login_password=_query_password)
- server.use(port=_query_server_port)
- setQueryName(server, "Glacial Teamspeak3-System(C)")
- return server
- # name: setQueryName
- # desc: set the display name of the connection
- def setQueryName(server, name):
- server.clientupdate(client_nickname=name)
- # name: getUID
- # desc: returns the UID
- # type: string
- def getUID(server, client_id):
- client = server.clientinfo(clid=client_id)[0]
- return client['client_unique_identifier']
- # name: getOnlineList
- # desc: get a list of online Users
- # type: list of UIDs
- def getOnlineList(server):
- clients = server.clientlist()
- uids = []
- for client in clients:
- if not "1" == client['client_type']:
- uids.append((getUID(server, client['clid']),client['clid']))
- clean_uids = []
- for uid in uids:
- for uid2 in uids:
- if uid[0] == uid2[0]:
- clean_uids.append(uid)
- return clean_uids
- # name: addRank
- # desc: Add a rank to a UID
- def addRank(server, UID, group):
- print(group)
- groups = getGroups(server, UID)
- if str(group) in groups:
- return
- server.servergroupaddclient(
- cldbid=("%i" % getCLDBID(server, UID)), sgid=("%i" % group))
- # name: delRank
- # desc: remove a rank from a UID
- def delRank(server, UID, group):
- groups = getGroups(server, UID)
- if str(group) in groups:
- server.servergroupdelclient(
- cldbid=("%i" % getCLDBID(server, UID)), sgid=("%i" % group))
- # name: getCLDBID
- # desc: get The CLDBID from UID
- # type: int
- def getCLDBID(server, UID):
- response = server.clientgetdbidfromuid(cluid=UID)[0]
- return int(float(response['cldbid']))
- # name: getGroups
- # desc: get Groups from UID
- # type: list
- def getGroups(server, UID):
- response = server.servergroupsbyclientid(
- cldbid="%i" % getCLDBID(server, UID))
- ret = []
- for e in response:
- ret.append(e['sgid'])
- return ret
- # MongoDB
- # name: alreadyExists
- # desc: return if a UID exists in the db
- def alreadyExists(db, UID):
- if db.users.find_one({"UID": UID}):
- return True
- return False
- # name: getUser
- # desc: return a User by UID
- def getUser(db, UID):
- return db.users.find_one({"UID": UID})
- # name: getName
- # desc: returns the UserName
- # type: string
- def getName(server, UID):
- try:
- client = server.clientdbinfo(cldbid=getCLDBID(server, UID))[0]
- return client['client_nickname']
- except:
- print(UID)
- return "ERROR"
- def setChannelName(server,cid,name):
- server.channeledit(cid=cid,channel_name=name)
- def getTotalPoints(db):
- ret = 0
- uids = db.users.find({})
- for uid in uids:
- ret += uid["Points"]
- return ret
- def getMonthPoints(db):
- ret = 0
- uids = db.users.find({})
- for uid in uids:
- if "monthly_Points" in uid:
- ret += uid["monthly_Points"]
- return ret
- # General
- # name: addPoints
- # desc: add Points to online users
- def addPoints(db, server):
- onlinelist = getOnlineList(server)
- users = db.users
- # Add every user wich is online 1 Point
- for user_cid in onlinelist:
- user_id = user_cid[0]
- user = getUser(db, user_id)
- idle = False
- try:
- idletime = int(server.clientinfo(clid = user_cid[1])[0]["client_idle_time"])
- if idletime > 960000:
- if "Name" in user:
- print( "IDLE " + user["Name"] + " " + str(idletime))
- idle = True
- except Exception as e:
- print("[ERROR]")
- if user:
- if not idle:
- mon_points = 1 * _point_mul
- if "monthly_Points" in user:
- mon_points += user['monthly_Points']
- users.update_one({'_id': user['_id']}, {
- '$set': {'Points': (user['Points'] + 1 * _point_mul),
- 'Name' : getName(server,user_id),
- 'monthly_Points':mon_points
- }
- }
- )
- else:
- print("IDLE")
- user = getUser(db, user_id)
- groups = getGroups(server, user_id)
- if "6" in groups:
- users.update_one({'_id': user['_id']}, { '$set': {'Admin': 3 }})
- else:
- users.update_one({'_id': user['_id']}, { '$set': {'Admin': 0 }})
- if True:
- # they are ok, but a bit freaked
- given_this = []
- taken_this = []
- for rank in _rank_list:
- if rank[0] < user['Points'] and (rank[1] >= user['Points']):
- given_this.append(rank[2])
- elif rank[0] < user['Points'] and rank[1] == 0:
- # if rank limit = 0 then it hasn't a limit
- given_this.append(rank[2])
- elif rank[2] not in given_this:
- taken_this.append(rank[2])
- if "Name" in user:
- print(user['Name'])
- else:
- print("NoName? : " + user['UID'])
- print(given_this)
- print(taken_this)
- for i in given_this:
- addRank(server, user['UID'], i)
- for i in taken_this:
- if i not in given_this:
- delRank(server, user['UID'], i)
- else:
- data = {'UID': user_id, 'Points': 0}
- print(users.insert_one(data).inserted_id)
- # debug:
- def updateStats(db,server):
- #NutzerAnzahl
- users = db.users.find().count()
- musers = db.users.find({"monthly_Points":{"$gt":0}}).count()
- #Punkte
- points = getTotalPoints(db)
- #mpoints = getMonthPoints(db)
- user_string = "[cspacer]Nutzer: {} ({})".format(users,musers)
- points_string = "[cspacer]Punkte: {} ~{:.1f} Jahre".format(points,points/4.0/24/365)
- #mpoints_string = "[cspacer]Diesen Monat: {} ~{:.1f} Monate".format(mpoints,mpoints/4.0/24/31)
- print( user_string)
- try:
- setChannelName(server,_user_channel,user_string)
- except Exception as e:
- pass
- print( points_string)
- try:
- setChannelName(server,_Points_channel,points_string)
- except Exception as e:
- pass
- #print( mpoints_string)
- #try:
- # setChannelName(server,_monthly_Points_channel,mpoints_string)
- #except Exception as e:
- # pass
- setChannelName(server,_refreshed_channel,"[cspacer]Aktualisiert um {} Uhr".format(time.strftime("%H:%M")))
- def main():
- loadRanks()
- server = getQueryConnection()
- client = MongoClient(_mongoDB_URL)
- db = client.penguin_production
- #db.authenticate(_mongoDB_user, _mongoDB_pass)
- addPoints(db, server)
- #updateStats(db,server)
- if "__main__" == __name__:
- main()
- else:
- print("Loading Points module")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement