Advertisement
Guest User

Untitled

a guest
Nov 11th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.62 KB | None | 0 0
  1. import ts3
  2. from pymongo import MongoClient
  3. import time
  4. import configparser
  5.  
  6. ## Variables ##
  7.  
  8. # TS3 Query
  9.  
  10. # type: string
  11. # desc: Server Adress
  12. _query_server = "127.0.0.1"
  13.  
  14. # type: int
  15. # desc: Query Port
  16. _query_port =
  17.  
  18. # type: int
  19. # desc: Server Port
  20. _query_server_port =
  21.  
  22. # type: string
  23. # desc: TS3 Query Username
  24. _query_username = ""
  25.  
  26. # type: string
  27. # desc: TS3 Query Password
  28. _query_password = ""
  29.  
  30. # type: bool
  31. # desc: is Config loaded
  32. _query_configLoaded = False
  33.  
  34. # MongoDB
  35.  
  36. # type: string
  37. # desc: MongoDB URL
  38. # default: 'mongodb://localhost:27017'
  39. _mongoDB_URL = "mongodb://localhost:27017"
  40.  
  41. _mongoDB_pass = "coin"
  42. _mongoDB_user = "bot"
  43. # Ranks
  44. # type: List of list of int
  45. # desc: Contains the Rankdata, every rank is a list, wich are in the list
  46. _rank_list = []
  47.  
  48. _point_mul = 1
  49.  
  50. _user_channel = 42
  51. _Points_channel = 43
  52. _monthly_Points_channel = 44
  53. _refreshed_channel = 45
  54.  
  55. ## Funcionts ##
  56.  
  57. # Loading
  58.  
  59. # name: loadQueryConfig
  60. # desc: loads the ports, address and userdata for the Query
  61.  
  62.  
  63. def loadQueryConfig():
  64. config = configparser.ConfigParser()
  65. config.read("/opt/coinsystem/config.cfg")
  66.  
  67. global _query_server
  68. global _query_port
  69. global _query_username
  70. global _query_password
  71. global _query_configLoaded
  72. global _query_server_port
  73. global _mongoDB_pass
  74. global _mongoDB_URL
  75. global _mongoDB_user
  76.  
  77. _query_server = config.get("SERVER", "ip")
  78. _query_port = config.getint("SERVER", "port")
  79. _query_server_port = config.getint("SERVER", "regular_port")
  80. _query_username = config.get("SERVER", "username")
  81. _query_password = config.get("SERVER", "password")
  82.  
  83. config = configparser.ConfigParser()
  84.  
  85. config.read("/opt/coinsystem/mongo.cfg")
  86. _mongoDB_URL = config.get("SERVER", "url")
  87. _mongoDB_user = config.get("SERVER", "username")
  88. _mongoDB_pass = config.get("SERVER", "password")
  89.  
  90. _query_configLoaded = True
  91.  
  92.  
  93. # name: loadRanks
  94. # desc: loads the ranks into the list
  95. def loadRanks():
  96. global _rank_list
  97. # open the ranks config and read every line
  98. with open("/opt/coinsystem/ranks.dat") as ranks:
  99. lines = ranks.readlines()
  100. for line in lines:
  101. # if not empty or comment
  102. if line != "\n" and "//" not in line:
  103. values = line.split(" ")
  104. _rank_list.append(
  105. [int(values[0]), int(values[1]), int(values[2])])
  106.  
  107.  
  108. # Query Functions
  109.  
  110.  
  111. # name: getQueryConnection
  112. # desc: returns a Query Connection and sets Displayname.
  113. # if not already loaded it also load the cofnig settings
  114. def getQueryConnection():
  115. if not _query_configLoaded:
  116. loadQueryConfig()
  117. server = ts3.query.TS3Connection(_query_server, _query_port)
  118. server.login(client_login_name=_query_username,
  119. client_login_password=_query_password)
  120. server.use(port=_query_server_port)
  121. setQueryName(server, "Glacial Teamspeak3-System(C)")
  122. return server
  123.  
  124. # name: setQueryName
  125. # desc: set the display name of the connection
  126.  
  127.  
  128. def setQueryName(server, name):
  129. server.clientupdate(client_nickname=name)
  130.  
  131. # name: getUID
  132. # desc: returns the UID
  133. # type: string
  134.  
  135.  
  136. def getUID(server, client_id):
  137. client = server.clientinfo(clid=client_id)[0]
  138. return client['client_unique_identifier']
  139.  
  140. # name: getOnlineList
  141. # desc: get a list of online Users
  142. # type: list of UIDs
  143.  
  144.  
  145. def getOnlineList(server):
  146. clients = server.clientlist()
  147. uids = []
  148. for client in clients:
  149. if not "1" == client['client_type']:
  150. uids.append((getUID(server, client['clid']),client['clid']))
  151. clean_uids = []
  152. for uid in uids:
  153. for uid2 in uids:
  154. if uid[0] == uid2[0]:
  155. clean_uids.append(uid)
  156. return clean_uids
  157.  
  158. # name: addRank
  159. # desc: Add a rank to a UID
  160.  
  161.  
  162. def addRank(server, UID, group):
  163. print(group)
  164. groups = getGroups(server, UID)
  165. if str(group) in groups:
  166. return
  167. server.servergroupaddclient(
  168. cldbid=("%i" % getCLDBID(server, UID)), sgid=("%i" % group))
  169.  
  170. # name: delRank
  171. # desc: remove a rank from a UID
  172.  
  173.  
  174. def delRank(server, UID, group):
  175. groups = getGroups(server, UID)
  176. if str(group) in groups:
  177. server.servergroupdelclient(
  178. cldbid=("%i" % getCLDBID(server, UID)), sgid=("%i" % group))
  179.  
  180.  
  181. # name: getCLDBID
  182. # desc: get The CLDBID from UID
  183. # type: int
  184. def getCLDBID(server, UID):
  185. response = server.clientgetdbidfromuid(cluid=UID)[0]
  186. return int(float(response['cldbid']))
  187.  
  188. # name: getGroups
  189. # desc: get Groups from UID
  190. # type: list
  191.  
  192.  
  193. def getGroups(server, UID):
  194. response = server.servergroupsbyclientid(
  195. cldbid="%i" % getCLDBID(server, UID))
  196. ret = []
  197. for e in response:
  198. ret.append(e['sgid'])
  199. return ret
  200. # MongoDB
  201.  
  202. # name: alreadyExists
  203. # desc: return if a UID exists in the db
  204.  
  205.  
  206. def alreadyExists(db, UID):
  207. if db.users.find_one({"UID": UID}):
  208. return True
  209. return False
  210.  
  211. # name: getUser
  212. # desc: return a User by UID
  213.  
  214.  
  215. def getUser(db, UID):
  216. return db.users.find_one({"UID": UID})
  217.  
  218. # name: getName
  219. # desc: returns the UserName
  220. # type: string
  221.  
  222.  
  223. def getName(server, UID):
  224. try:
  225. client = server.clientdbinfo(cldbid=getCLDBID(server, UID))[0]
  226. return client['client_nickname']
  227. except:
  228. print(UID)
  229. return "ERROR"
  230.  
  231.  
  232.  
  233. def setChannelName(server,cid,name):
  234. server.channeledit(cid=cid,channel_name=name)
  235.  
  236. def getTotalPoints(db):
  237. ret = 0
  238. uids = db.users.find({})
  239. for uid in uids:
  240. ret += uid["Points"]
  241. return ret
  242.  
  243. def getMonthPoints(db):
  244. ret = 0
  245. uids = db.users.find({})
  246. for uid in uids:
  247. if "monthly_Points" in uid:
  248. ret += uid["monthly_Points"]
  249. return ret
  250. # General
  251.  
  252. # name: addPoints
  253. # desc: add Points to online users
  254. def addPoints(db, server):
  255.  
  256. onlinelist = getOnlineList(server)
  257. users = db.users
  258.  
  259. # Add every user wich is online 1 Point
  260. for user_cid in onlinelist:
  261. user_id = user_cid[0]
  262. user = getUser(db, user_id)
  263. idle = False
  264. try:
  265. idletime = int(server.clientinfo(clid = user_cid[1])[0]["client_idle_time"])
  266. if idletime > 960000:
  267. if "Name" in user:
  268. print( "IDLE " + user["Name"] + " " + str(idletime))
  269. idle = True
  270. except Exception as e:
  271. print("[ERROR]")
  272. if user:
  273. if not idle:
  274. mon_points = 1 * _point_mul
  275. if "monthly_Points" in user:
  276. mon_points += user['monthly_Points']
  277. users.update_one({'_id': user['_id']}, {
  278. '$set': {'Points': (user['Points'] + 1 * _point_mul),
  279. 'Name' : getName(server,user_id),
  280. 'monthly_Points':mon_points
  281.  
  282. }
  283. }
  284.  
  285. )
  286. else:
  287. print("IDLE")
  288. user = getUser(db, user_id)
  289. groups = getGroups(server, user_id)
  290. if "6" in groups:
  291. users.update_one({'_id': user['_id']}, { '$set': {'Admin': 3 }})
  292. else:
  293. users.update_one({'_id': user['_id']}, { '$set': {'Admin': 0 }})
  294. if True:
  295. # they are ok, but a bit freaked
  296. given_this = []
  297. taken_this = []
  298. for rank in _rank_list:
  299. if rank[0] < user['Points'] and (rank[1] >= user['Points']):
  300. given_this.append(rank[2])
  301. elif rank[0] < user['Points'] and rank[1] == 0:
  302. # if rank limit = 0 then it hasn't a limit
  303. given_this.append(rank[2])
  304. elif rank[2] not in given_this:
  305. taken_this.append(rank[2])
  306.  
  307. if "Name" in user:
  308. print(user['Name'])
  309. else:
  310. print("NoName? : " + user['UID'])
  311. print(given_this)
  312. print(taken_this)
  313. for i in given_this:
  314. addRank(server, user['UID'], i)
  315. for i in taken_this:
  316. if i not in given_this:
  317. delRank(server, user['UID'], i)
  318. else:
  319. data = {'UID': user_id, 'Points': 0}
  320. print(users.insert_one(data).inserted_id)
  321. # debug:
  322.  
  323. def updateStats(db,server):
  324. #NutzerAnzahl
  325. users = db.users.find().count()
  326. musers = db.users.find({"monthly_Points":{"$gt":0}}).count()
  327. #Punkte
  328. points = getTotalPoints(db)
  329. #mpoints = getMonthPoints(db)
  330. user_string = "[cspacer]Nutzer: {} ({})".format(users,musers)
  331. points_string = "[cspacer]Punkte: {} ~{:.1f} Jahre".format(points,points/4.0/24/365)
  332.  
  333. #mpoints_string = "[cspacer]Diesen Monat: {} ~{:.1f} Monate".format(mpoints,mpoints/4.0/24/31)
  334. print( user_string)
  335. try:
  336. setChannelName(server,_user_channel,user_string)
  337. except Exception as e:
  338. pass
  339. print( points_string)
  340. try:
  341. setChannelName(server,_Points_channel,points_string)
  342. except Exception as e:
  343. pass
  344. #print( mpoints_string)
  345. #try:
  346. # setChannelName(server,_monthly_Points_channel,mpoints_string)
  347. #except Exception as e:
  348. # pass
  349. setChannelName(server,_refreshed_channel,"[cspacer]Aktualisiert um {} Uhr".format(time.strftime("%H:%M")))
  350. def main():
  351. loadRanks()
  352. server = getQueryConnection()
  353. client = MongoClient(_mongoDB_URL)
  354. db = client.penguin_production
  355. #db.authenticate(_mongoDB_user, _mongoDB_pass)
  356.  
  357. addPoints(db, server)
  358. #updateStats(db,server)
  359.  
  360. if "__main__" == __name__:
  361. main()
  362. else:
  363. print("Loading Points module")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement