-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
271 lines (238 loc) · 9.26 KB
/
bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
#! /usr/bin/env python
# -*- coding:utf-8 -*-
#
# @name : P4Discord - Perforce x Discord Monitor
# @url : https://github.com/Cisc0-gif
# @author : Cisc0-gif
import discord
import asyncio
import logging
import random
import sys
import os
import subprocess
import time
from datetime import datetime
# Go To https://discordapp.com/developers/applications/ and start a new application for Token
# **Enable MEMBER and MESSAGE intents**
#Get member intent to read users in server
intents = discord.Intents.default()
intents.members = True
client = discord.Client(command_prefix='/', description='Basic Commands', intents=intents)
TOKEN = ''
superuser = "" #superuser to manage admins and server
monitoring = False
logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s:%(message)s'))
logger.addHandler(handler)
def client_run():
os.system("start python webhook.py") #start webhook as side process with bot
client.loop.create_task(background_loop())
client.run(TOKEN)
def logwrite(msg): #writes chatlog to MESSAGES.log
with open('MESSAGES.log', 'a+') as f:
f.write(msg + '\n')
f.close()
async def background_loop():
await client.wait_until_ready()
while not client.is_closed:
print("Booted Up @ " + time.ctime())
logwrite("Booted Up @ " + time.ctime())
await asyncio.sleep(3600) #Bootup Message
@client.event
async def on_ready():
print('--------------------------------------------------------------------------------------')
print('Server Connect Link:')
print('https://discordapp.com/api/oauth2/authorize?scope=bot&client_id=' + str(client.user.id))
print('--------------------------------------------------------------------------------------')
print('Logged in as:')
print(client.user.name)
print("or")
print(client.user)
print("UID:")
print(client.user.id)
print('---------------------------------------------')
print("LIVE CHAT LOG - See MESSAGES.log For History")
print("---------------------------------------------")
if os.path.exists("game_presence.txt") and os.path.getsize("game_presence.txt") > 0:
try:
f = open("game_presence.txt","r")
if f.mode == 'r':
contents = f.read()
await client.change_presence(activity=discord.Game(contents), status=discord.Status.online)
finally:
f.close()
else:
try:
f = open("game_presence.txt", "w")
if f.mode == "w":
f.write("DEFAULT PRESENCE")
finally:
f.close()
await client.change_presence(activity=discord.Game("DEFAULT PRESENCE"), status=discord.Status.online)
@client.event
async def on_message(message):
if message.author == client.user:
return #ignore what bot says in server so no message loop
channel = message.channel
print(message.author, "said:", message.content, "-- Time:", time.ctime()) #reports to discord.log and live chat
logwrite(str(message.author) + " said: " + str(message.content) + "-- Time: " + time.ctime())
def get_members():
guild = message.guild
if guild:
members = guild.members
member_names = [member.name for member in members]
return member_names
def server_status():
proc = subprocess.Popen(["p4", "info"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, shell=True)
(out, err) = proc.communicate()
if str(out) == "b''":
return False
else:
return True
#check if user has admin privileges
async def check_admin():
try:
f = open("admins.txt","r")
if f.mode == 'r':
contents = f.read()
finally:
f.close()
if str(message.author) not in contents and superuser not in str(message.author):
await channel.send(":ERROR: Only promoted users can run this command")
raise asyncio.CancelledError()
else:
pass
#check if user has superuser privileges
async def check_superuser():
if superuser not in str(message.author):
await channel.send(":ERROR: Only " + superuser + " can run this command")
raise asyncio.CancelledError()
else:
pass
async def server_monitor():
if monitoring == True:
if server_status() == False:
await message.author.send(":NOTICE: Perforce Server has gone offline!")
result = subprocess.check_output(["wmic", "logicaldisk", "get", "name"])
if b'D:' not in result:
await message.author.send(":NOTICE: D: drive disconnected!")
raise asyncio.CancelledError()
await asyncio.sleep(5)
await server_monitor()
else:
raise asyncio.CancelledError()
#start perforce server + broker
if message.content == "/p4 start":
await check_admin()
if server_status() == False:
monitoring = True
os.system("start /b p4d")
os.system("start /b D:\HelixCoreBroker\p4broker.exe")
await channel.send("Perforce Server starting...")
await channel.send("Helix Core Broker starting...")
await server_monitor() #call after so it doesn't declare the server offline prematurely
else:
await channel.send(":ERROR: Perforce Server is already running!")
#stop perforce server
elif message.content == "/p4 stop":
await check_admin()
if server_status() == True:
monitoring = False
os.system("p4 admin stop")
await channel.send("Perforce Server stopped...")
else:
await channel.send(":ERROR: Perforce Server is offline!")
#get server status
elif message.content == "/p4 status":
if server_status() == False:
await channel.send("Perforce Server: OFFLINE")
else:
await channel.send("Perforce Server: ONLINE")
#check if storage drive connected
elif message.content == "/p4 checkdrive":
result = subprocess.check_output(["wmic", "logicaldisk", "get", "name"])
if b'D:' in result: #CHANGE DRIVE NAME HERE
await channel.send("D: drive connected")
else:
await channel.send("D: drive not connected")
#change Discord Game Presence
elif "/p4 presence" in message.content:
await check_superuser()
cmd = message.content.split()
game = str(cmd[len(cmd)-1])
try:
f = open("game_presence.txt","w")
if f.mode == 'w':
f.write(game)
await client.change_presence(activity=discord.Game(game),status=discord.Status.online)
finally:
f.close()
await channel.send("Bot presence updated to " + game + "!")
#promote user to admin
elif "/p4 promote" in message.content:
await check_superuser()
cmd = message.content.split()
user = str(cmd[len(cmd)-1])
member_names = get_members()
if user in member_names:
with open("admins.txt", "r") as f:
admins = f.read()
if user not in admins: #check if user in admins
try:
f = open("admins.txt", "a")
if f.mode == "a":
f.write(user + '\n')
await channel.send(user + " was promoted to admin")
finally:
f.close()
else:
await channel.send(user + " is already an admin")
else:
await channel.send(user + " is not in this server")
#demote admin to user
elif "/p4 demote" in message.content:
await check_superuser()
cmd = message.content.split()
user = str(cmd[len(cmd)-1])
with open("admins.txt", "r") as f:
admins = f.read()
if user in admins: #check if user in admins
try:
with open("admins.txt", "r") as f:
lines = f.readlines()
lines = [line for line in lines if line.strip() != user.strip()]
with open("admins.txt", "w") as f:
f.writelines(lines)
await channel.send(user + " was demoted")
finally:
f.close()
else:
await channel.send(user + " not found in admins")
#view all users in server
elif message.content == "/p4 users":
await check_superuser()
member_names = get_members()
await channel.send('\n'.join(member_names))
#view all admins
elif message.content == "/p4 admins":
await check_superuser()
if os.path.getsize("admins.txt") > 0:
try:
f = open("admins.txt","r")
if f.mode == 'r':
contents = f.read()
await channel.send(contents)
finally:
f.close()
else:
await channel.send(":ERROR: No admins found.")
elif message.content == "/p4 help":
if superuser in str(message.author): #only send superuser commands to superuser
await message.author.send("========P4Discord *Superuser* Commands========\n/p4 promote Promote user to admin\n/p4 demote Demote admin to user\n/p4 users Get list of all members in server\n/p4 admins Get list of all admin users\n/p4 presence Updated Discord Presence")
await channel.send("========P4Discord Commands========\n/p4 start Start Helix Core Server + Broker\n/p4 stop Stop Helix Core Server\n/p4 status Get server status\n/p4 checkdrive Get status of storage drive\n/p4 help Display this menu")
elif "/p4" in message.content:
await channel.send(":ERROR: Unknown command. Use '/p4 help' to view commands")
client_run()