Python Development (Discord, TS, Web Integration)

Status
This thread has been locked.

NoobSkills

Owner of Legionwars
Supreme
Feedback score
2
Posts
382
Reactions
146
Resources
0
NOTE: I'm posting this for my friend. I am not the developer.

Offering cheap python development for anyone that needs it. Can create basic Discord Bots, Teamspeak Integration Apps, Website Integration (Provided API Access), and anything else that you want automated.

Past work:
Code:
"""
-----
Creator: Jackdevo
Upload Date: 23/06/2018
Purpose of Upload: To showcase Python Development knowledge to the MC-Market community
Purpose of Code: An integration program for an Arma 3 Community, which integrates the use of Web, Teamspeak, Sqlite and the Discord API to create a fully functional, but still early stage development management platform.
Copyright: Reserved. Permission granted to NoobSkills for posting in the MC-Market Community
Notes: All important API Keys, Webhooks etc that may provide unauthorised access to otherwise non publicly available information - these are clearly marked with 'REDACTED FOR PROTECTION'. Each Python file is clearly indicated.
-----
"""
#====================================
### Name: main.py
## Purpose: Brings together all other code files and functions, to run the master program
#====================================

from server import server
from forum import forum
from discord import discord
from gsheets import gsheets
from teamspeak import teamspeak

server = server()
forum = forum()
discord = discord()
gsheets = gsheets()
teamspeak = teamspeak()

#mMySQL Database Setup
import mysql.connector
cnx = mysql.connector.connect(user='root', password='REDACTED',
                              host='127.0.0.1',
                              database='REDACTED',
                              autocommit =True)
cursor = cnx.cursor()

#Other Import
import time


"""
Valid Functions: Forums
forum.convert("URL") #When given forum link, returns users forum ID as INT value
forum.getGroups(3) #When given a users forum ID, returns their primary and secondary groups inm format: [PrimaryGroupID, [SecondaryGroupID's]]
forum.addGroup(member, group) #When given member ID and group ID, assigns that member to the forum group

Valid Functions: Server
server.whitelistNHS(pid, level) #Whitelist someone as a main NHS Rank
server.whitelistPolice(pid, level) #Whitelist someone as a main Police Rank

Valid Functions: Discord
discord.online() #Send "Whitelisting Activated" to Discord Logs Channel
discord.offline() #Send "Whitelisting Deactivated" to Discord Logs Channel
discord.send(msg) #Sends message to Discord Logs Channel

Valid Functions: Gshseets
gsheets.convert_rank() #Converts given faction rank to numeric value. Later will be expanded to convert branch tier into license name
gsheets.pull_polData() #Returns values from Police Database in format: [[Name,PID,TSDBID,ForumLink,NumRank,WhitelistedStatus,Constab]]
gsheets.pull_NHSData() #Returns values from NHS Database in format: [[Name,PID,TSDBID,ForumLink,NumRank,WhitelistedStatus]]
gsheets.checkWhitelisting() #Checks Whitelisting Database to ensure that whitelisting has been enabled by management

Valid Functions: Teamspeak
teamspeak.group_to_id(group) #Input teamspeak group name, and it will convert it to the group ID if it is in the list in the function
teamspeak.client_list() #Returns a list of teamspeak clients and details about them
teamspeak.add_group(groupID,DBID) #Enter groupID and Teamspeak Members DBID, it will add the group to the member
teamspeak.remove_group(groupIDm DBID) #Enter groupID and Teamspeak Members DBID, it will remove the group from the member

Valid Functions: Main
main.run() #Runs auto rank whitelister
main.runRankWhitelist() #Whitelists Police and NHS Members to their current Server Ranks (Only for main rank whitelisting, not branches) #Currently only does teamspeak and forum whitelisting
"""



class main:

    def runRankWhitelist(self):
        pollist = gsheets.pull_polData()
        nhslist = gsheets.pull_NHSData()


        #NHS Whitelisting
        if nhslist != []:
            print("Whitelisting NHS Members")
            for x in range(0, len(nhslist)):
                if nhslist[x][5] != "Yes":
                    nhstextrank = nhslist[x][4]
                    nhsnumrank = gsheets.convert_rank(nhslist[x][4])
                    nhslist[x][4] = nhsnumrank
                    server.whitelistNHS(nhslist[x][1], nhsnumrank)
                    text = "Whitelisting: "+str(nhslist[x][0])+", PID: "+str(nhslist[x][1])+", as NHS Level: "+str(nhstextrank)
                    print(text)
                    discord.send(text)

                    if nhsnumrank == 0:
                        text = "NOT DONE YET"
                    else:
                        text = "Adding: " + str(nhslist[x][0]) + " To Server Group: " + str(nhstextrank)
                        teamspeak.add_group(nhstextrank,nhslist[x][2])
                        print(text)
                        discord.send(text)
                        time.sleep(3) #To avoid teamspeak flood ban


        #Police Whitelisting
        if pollist != []:
            print("Whitelisting Police Members")
            for x in range(0, len(pollist)):
                if pollist[x][5] != "Yes":
                    poltextrank = pollist[x][4]
                    polnumrank = gsheets.convert_rank(pollist[x][4])
                    pollist[x][4] == polnumrank
                    server.whitelistPolice(pollist[x][1], polnumrank)
                    text = "Whitelisting: "+str(pollist[x][0])+", PID: "+str(pollist[x][1])+", as Police Level: "+str(poltextrank)
                    print(text)
                    discord.send(text)


                    if polnumrank == 0:
                        text = "NOT DONE YET"
                    else:
                        groupslist = []
                        groupslist.append(pollist[x][4])
                        if polnumrank >= 10: #If greater than or equal to cop rank 11
                            groupslist.append("Gold Command") #Add servergroup Gold Command
                        if 10 > polnumrank >= 8: #If greater than or equal to cop rank 8
                            groupslist.append("Silver Command")  # Add servergroup Silver Command
                        if 8 > polnumrank >= 5: #If greater than or equal to cop rank 5
                            groupslist.append("Bronze Command")  # Add servergroup Bronze Command

                        groupslist.append(pollist[x][6]) #Adding Constab to this list

                        text = "Adding: " + str(pollist[x][0]) + " To Server Groups "+str(groupslist)
                        print(text)
                        discord.send(text)
                        for y in range(0, len(groupslist)):
                            group = groupslist[y]
                            teamspeak.add_group(group,pollist[x][2])
                            time.sleep(3) #To avoid teamspeak flood ban



    def run(self):
        print("Whitelisting System Online")
        discord.online()
        while True:
            check = gsheets.checkWhitelisting()
            if check == bool(True):
                self.runRankWhitelist()
                print("Sleeping for 30 seconds...")
                time.sleep(30)
            else:
                print("Sleeping for 60 seconds...")
                time.sleep(60)





    def runRankWhitelistAll(self): #USE INCASE OF WHITELISTING ISSUE ONLY!!
        print("USE GOOGLE SHEETS AND PULL EVERYONE FROM DATABASES,, REGARDLESS OF WHITELISTED VALUE OR NOT")
        print("MAKE CLEAR THIS IS JUST FOR RANKS")
        print("SET THIS SO IT WHITELISTS EVERYONE ON MYSQL DATABASE AS RANK 0 FOR BOTH FACTIONS FIRST")


main = main()
main.run()

#EVENTUALLY CHANGE IT SO THAT THE PROGRAM GOES INTO POLICE AND NHS MASTER DATABASES AND AUTO SETS WHITELISTED VALUE TO TRUE.
#FOR NOW, FACTION LEADS WILL HAVE TO LOOK AT DISCSORD LOGS THEN TURN THE VALUE TO FALSE

#====================================
### Name: teamspeak.py
## Purpose: Uses the teamspeak APi to do various functions
#====================================

#Install Command: pip3.6 install ts3
#Update Command: pip3.6 install --upgrade ts3
#In below documentation, also a massive code file with all examples (Written in python)
#Command Documentation: https://py-ts3.readthedocs.io/en/latest/api/commands.html
#Other Documentation: https://media.readthedocs.org/pdf/py-ts3/latest/py-ts3.pdf
#Add Client to ServerGroup: servergroupaddclient sgid={groupID} cldbid={clientDBID}
#Remove Client from ServerGroup: servergroupdelclient sgid={groupID} cldbid={clientDBID}
#
#MOST CODE FROM HERE: https://pydigger.com/pypi/ts3


"""
import ts3

#ts3conn.PUTCOMMANDFUNCTIONHERE()
with ts3.query.TS3Connection("REDACTED", 10011) as ts3conn:
    ts3conn.login(client_login_name="tsbot", client_login_password="REDACTED")
    ts3conn.use(sid=1)
"""

import ts3


class teamspeak:

    def group_to_id(self, group): #HIGHLY, HIGHLY INNEFICIENT, NEED TO CHANGE TO DICTIONARY OR SOMETHING THAT USES LISTS!!!!
        if group == "CSO":
            return 28
        elif group == "PCSO":
            return 29
        elif group == "C":
            return 30
        elif group == "SC":
            return 31
        elif group == "SGT":
            return 32
        elif group == "DSGT":
            return 33
        elif group == "INS":
            return 34
        elif group == "CI":
            return 35
        elif group == "SI":
            return 36
        elif group == "CSI":
            return 37
        elif group == "ACC":
            return 38
        elif group == "DCC":
            return 39
        elif group == "CC":
            return 40
        elif group == "Kavala":
            return 100
        elif group == "Athira":
            return 101
        elif group == "Pyrgos":
            return 102
        elif group == "Bronze Command":
            return 104
        elif group == "Silver Command":
            return 105
        elif group == "Gold Command":
            return 106
        elif group == "STU":
            return 71
        elif group == "FA":
            return 72
        elif group == "NUR":
            return 73
        elif group == "PAR":
            return 74
        elif group == "DOC":
            return 75
        elif group == "SDOC":
            return 76
        elif group == "SUR":
            return 77
        elif group == "CST":
            return 78
        elif group == "DCMO":
            return 79
        elif group == "CMO":
            return 80
        elif group == "N/A":
            return False
        else:
            return False


    def client_list(self):
        with ts3.query.TS3Connection("REDACTED") as ts3conn:
            ts3conn.login(
                client_login_name="REDACTED",
                client_login_password="REDACTED"
            )
            ts3conn.use(sid=1)
        resp = ts3conn.clientlist()
        print("Clients on the server:", resp.parsed)
        print("Error:", resp.error["id"], resp.error["msg"])

        for client in resp.parsed:
            return(client)
        for client in resp:
            return(client)

    def add_group(self, group_id, client_dbid):
        #print("Teamspeak whitelisting is disabled until TS is hosted on the main server - To protect IP's")
        #return #DELETE THIS RETURN AND PRINT WHEN ACTIVATED AGAIN!!!!!!

        if group_id is not int:
            group_id = self.group_to_id(group_id)
            if group_id == False:
                return
        try:
            client_dbid = int(client_dbid)
        except:
            print("Error whitelisting Teamspeak Ranks")
            return

        #try:
        with ts3.query.TS3Connection("REDACTED") as ts3conn:
            ts3conn.login(
                client_login_name="REDACTED",
                client_login_password="REDACTED"
            )
            ts3conn.use(sid=1)

            try:
                ts3conn.servergroupaddclient(sgid=group_id, cldbid=client_dbid)
            except:
                print("Error, is user with DBID: "+str(client_dbid)+", already in Group ID: "+str(group_id)+"?")
        #except:
        #    print("Teamspeak Add Grooup Function Crashed...")


    def remove_group(self, group_id, client_dbid):
        try:
            with ts3.query.TS3Connection("REDACTED") as ts3conn:
                ts3conn.login(
                    client_login_name="REDACTED",
                    client_login_password="REDACTED"
                )
                ts3conn.use(sid=1)

                try:
                    ts3conn.servergroupdelclient(sgid=group_id, cldbid=client_dbid)
                except:
                    print("Error, is user with DBID: "+str(client_dbid)+", already not in Group ID: "+str(group_id)+"?")
        except:
            print("Teamspeak Remove Grooup Function Crashed...")

"""
# !/usr/bin/python3

import ts3

with ts3.query.TS3Connection("REDACTED") as ts3conn:
    ts3conn.login(
        client_login_name="tsbot",
        client_login_password="REDACTED"
    )
    ts3conn.use(sid=1)

    ts3conn.servergroupaddclient(sgid=36, cldbid=2)

"""

"""
import ts3

with ts3.query.TS3Connection("REDACTED") as ts3conn:
    ts3conn.login(
        client_login_name="REDACTED",
        client_login_password="REDACTED"
    )
    ts3conn.use(sid=1)

    ts3conn.servergroupaddclient(sgid=36, cldbid=2)

"""

====================================
### Name: server.py
## Purpose: Uses the SQLite Interface to whitelist players on Arma Server
====================================

#mMySQL Database Setup
import mysql.connector
cnx = mysql.connector.connect(user='root', password='REDACTED',
                              host='127.0.0.1',
                              database='REDACTED',
                              autocommit =True)
cursor = cnx.cursor()

class server:
    def whitelistNHS(self, pid, level):
        #Final Quote removal check
        pid = pid.replace('"', '')
        #Whitelisting
        cursor.execute("UPDATE players SET mediclevel = %s WHERE pid = %s", (level, pid))

    def whitelistPolice(self, pid, level):
        #Final Quote removal check
        pid = pid.replace('"', '')
        #Whitelisting
        cursor.execute("UPDATE players SET coplevel = %s WHERE pid = %s", (level, pid))

====================================
### Name: gsheets.py
## Purpose: Uses the Google Sheets API to retrieve information from  GSheets Spreadsheets
====================================

#Setting up Google Sheets API
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('REDACTED', SCOPES)
    creds = tools.run_flow(flow, store)
service = build('sheets', 'v4', http=creds.authorize(Http()))


class gsheets:

    def convert_rank(self, rank):
        try:
            rank == int(rank)
            return rank
        except:
            nhsList = ["N/A","STU","FA","NUR","PAR","DOC","SDOC","SUR","CST","DCMO","CMO"]
            polList = ["N/A","CSO","PCSO","C","SC","SGT","DSGT","INS","CI","SI","CSI","ACC","DCC","CC"]
            try:
                return nhsList.index(rank)
            except:
                return polList.index(rank)


    def pull_polData(self):
        print("Gathering Police Data")
        sheetid = 'REDACTED'
        sheetrange = 'REDACTED'
        result = service.spreadsheets().values().get(spreadsheetId=sheetid,
                                                     range=sheetrange).execute()
        updated = result.get('values',[]) #Raw data in format [[Name, PID, TSUID, ForumLink,Rank,WhitelistStatus,Constab,JoinDate,LastPromo, etc......],[],[],[]]

        validList = []
        for a in range(0, len(updated)):
            try:
                if updated[a][1] != "":
                    try:
                        validList.append([updated[a][0],updated[a][1],updated[a][2],updated[a][3],updated[a][4],updated[a][5],updated[a][6]]) #Format = [[Name,PID,TSUID,ForumLink,NumRank,WhitelistedStatus,Constab]]
                    except:
                        pass
            except:
                pass
        return validList


    def pull_NHSData(self):
        print("Gathering NHS Data")
        sheetid = 'REDACTED'
        sheetrange = 'REDACTED'
        result = service.spreadsheets().values().get(spreadsheetId=sheetid,
                                                     range=sheetrange).execute()
        updated = result.get('values',[]) #Raw data in format [[Name, PID, TSUID, ForumLink,Rank,WhitelistStatus,JoinDate, LastPromo, etc......],[],[],[]]
        validList = []
        for a in range(0, len(updated)):
            try:
                if updated[a][1] != "":
                    try:
                        validList.append([updated[a][0],updated[a][1],updated[a][2],updated[a][3],updated[a][4],updated[a][5]]) #Format = #Format = [[Name,PID,TSUID,ForumLink,NumRank,WhitelistedStatus]]
                    except:
                        pass
            except:
                pass
        return validList


    def checkWhitelisting(self):
        print("Checking Status")
        sheetid = 'REDACTED'
        sheetrange = 'REDACTED'
        result = service.spreadsheets().values().get(spreadsheetId=sheetid,
                                                     range=sheetrange).execute()
        result = result.get('values', [])
        result = result[0][0]

        if result == "Activated":
            print("Whitelisting Online")
            return bool(True)
        else:
            print("Whitelisting Offline. Re-enable it in the Whitelisting Database")
            return bool(False)

====================================
### Name: forum.py
## Purpose: Uses the Invision Community API to whitelist people on the Forum Website
====================================

import requests
from discord import discord
discord = discord()
#--------------
#Main Variables
#--------------

baseurl = "REDACTED"  # URL Of API
key = "REDACTED"  # API Key
# API Endpoints listed here: REDACTED
endpoint = "REDACTED"  # Where the API request will go

#--------------
#Group ID Variables
#--------------
#REDACTED INFO HERE

class forum:

    #Converts given URL to an INT Value of that members ID and returns this value
    def convert(self, url):
        try:
            url = url.replace("REDACTED", "")
            index = url.find("-")
            url = url[0:index]
            url = int(url)
        except:
            pass
        return url


    def getGroups(self, member):
        endpoint = str("/core/members/"+str(member))

        params = {
            'key': key
        }
        result = requests.get(baseurl + endpoint, params=params).json()
        #Getting Primary Group Information
        print(result)
        try:
            result = result['results']
            result = dict(result[0])
            group = result['primaryGroup']  # Getting Primary Group from Result dictionary
        except:
            group = result['primaryGroup']  # Getting Primary Group from Result dictionary


        primGroupID = group['id'] #Saving Primary Group ID
        group = result['secondaryGroups']  # Getting Secondary Groups from Result dictionary.
                                           #Returns as list with multiple dictioanries inside
        secondaryGroupIDS = []
        for x in range(0, len(group)):
            secondaryGroupIDS.append(group[x]['id'])
        groups = [primGroupID, secondaryGroupIDS] #FORMAT = [PrimaryGroupID, [SecondaryGroupID's]]
        return groups


    def addGroup(self, member, group):
        member = self.convert(str(member)) #If forum link accidentally put in, this function will ensure it is changed to an Integer value
        try:
            group = int(group)
        except:
            return False
        endpoint = str("REDACTED" + str(member))
        groups = self.getGroups(member)
        #Checking if Primary Group is empty. If it use, group will be set as Primary Group
        if groups[0] == reg_member:
            params = {
                'key': key,
                'group': groups[0]
            }
        elif groups[0] == group:
            return {}
        #If there is already a set primary group, the added group will be set to be the Secondary Group
        elif group not in groups[1]:
            #Creating new groups list, with all the users current secondary groups
            newgroups = groups[1]
            #Appending the group to be added, to the new secondary groups list
            newgroups.append(group)


            groupsstr = ""
            for x in range(0, len(newgroups)):
                groupsstr += str(newgroups[x])+","

            print(groupsstr)

            params = {
                'key': key,
                'secondaryGroups': groupsstr
            }
        else:
            return {}

        #Running the API
        result = requests.post(baseurl + endpoint, params=params).json()
        #Returns the resul of the API
        return result



#CURRENTLY ONLY CAN ADD GROUPS TO MAIN GROUP THING IF IT MEETS THE CONDITIONS, FOR SOME REASON CANNOT ADD A SECONDARY GROUP!!!!






    def donate(self):
        print("Test") #NEED TO MAKE THIS FUNCTION


"""
----------
Valid Functions when 'test = forum()'
----------
id = test.convert("URL") #When given forum link, returns users forum ID as INT value
groups = test.getGroups(3) #When given a users forum ID, returns their primary and secondary groups inm format: [PrimaryGroupID, [SecondaryGroupID's]]


"""

#====================================
### Name: discord.py
## Purpose: Post notifications within Discord
#====================================

import requests
from discord_hooks import Webhook
url = 'REDACTED'


class discord:

    def online(self):
        msg = Webhook(url, msg= "Whitelisting System Online")
        msg.post()

    def offline(self):
        msg = Webhook(url, msg= "Whitelisting System Offline")
        msg.post()

    def send(self, message):
        msg = Webhook(url, msg = message)
        msg.post()
Contact me on discord if you are interested!
Jackdevo#9525
 
PebbleHost
High performance, consistent uptime and fast support. Minecraft hosting that just works.
Status
This thread has been locked.
Top