-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
176 lines (138 loc) · 5.67 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
import discord
import os
import yaml
from kubernetes import client, config
from google.cloud import storage
# Discord auth token
DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN")
NAMESPACE = os.environ.get("NAMESPACE")
GCP_GS_BUCKET = os.environ.get("GCP_GS_BUCKET")
ADMIN_FILE = "config/admins.txt"
JOBS = {
"restore-sql-backup": "./jobs/restore-sql-backup/job-restore-sql-backup.yaml",
"example-job": "./jobs/example-job/job-example-job.yaml"
}
IN_CLUSTER = True
DEPLOYMENT_NAME = "discord_opsbot"
GCP_CREDS_PATH = "/etc/gcp-sa/service-account.json"
def load_admins():
with open(ADMIN_FILE) as f:
admins = list()
for line in f.readlines():
admin = line.strip()
admins.append(admin)
return admins
def load_kube_config(config):
if IN_CLUSTER:
config.load_incluster_config()
else:
config.load_kube_config()
class Commands:
def __init__(self):
self.commands = {
"help": self.help,
"test": self.test,
"version": self.version,
"jobs": self.jobs,
"jobs-status": self.jobs_status,
"create-job": self.create_job,
"list-backups": self.list_backups,
}
async def help(self, message):
'''dispalys help message'''
send_str = "```"
for command, command_func in self.commands.items():
send_str += f"{command} - {command_func.__doc__}\n"
send_str += "```"
await message.channel.send(send_str)
async def version(self, message):
'''gets the currently deployed version'''
load_kube_config(config)
v1 = client.AppsV1Api()
i = v1.read_namespaced_deployment(DEPLOYMENT_NAME, NAMESPACE)
image_ver = i.spec.template.spec.containers[0].image.split(":")[1]
send_str = f"```version: {image_ver}```"
await message.channel.send(send_str)
async def test(self, message):
'''sends a test message'''
await message.channel.send('Hello!')
async def jobs(self, message):
'''lists creatable jobs'''
send_str = "```"
for job_name, job_path in JOBS.items():
send_str += f"{job_name} - {job_path}\n"
send_str += "```"
await message.channel.send(send_str)
async def jobs_status(self, message):
'''shows status of all jobs in the namespace'''
load_kube_config(config)
v1 = client.BatchV1Api()
send_str = "```"
send_str += "Jobs status:\n"
ret = v1.list_namespaced_job("persistent-outreach")
send_str += "NAMESPACE\t\t\tSTART TIME\t\t\t\t\tJOB NAME\t\t\t\t\tTOTAL\tREADY\tFAILED\tSUCCEEDED\n"
for i in ret.items:
send_str += f"{i.metadata.namespace}\t{i.status.start_time}\t{i.metadata.name}\t{i.spec.completions}\t\t{i.status.ready or 0}\t\t{i.status.failed or 0}\t\t{i.status.succeeded or 0}\n"
send_str += "```"
await message.channel.send(send_str)
async def create_job(self, message):
'''creates a job. jobs must be packaged with the bot'''
load_kube_config(config)
message_split = message.content.split(" ")
if len(message_split) < 3:
await message.channel.send(f"USAGE: create_job [job_name]")
return
job_name = message_split[2]
job_path = JOBS.get(job_name)
if job_path is None:
await message.channel.send(f"No job definition found for: `{job_name}`")
return
if job_name == "restore-sql-backup":
if len(message_split) != 4:
await message.channel.send(f"USAGE: create_job restore-sql-backup [target_gcs_file] ")
target_file = message_split[3]
with open(job_path) as f:
job_def = yaml.safe_load(f)
job_def['spec']['template']['spec']['containers'][0]['env'][0]['value'] = target_file
v1 = client.BatchV1Api()
v1.create_namespaced_job(namespace=NAMESPACE, body=job_def)
await message.channel.send(f"Job created: `{job_name}`")
return
await message.channel.send(f"Job doesn't appear to be implemented yet: `{job_name}`")
return
async def list_backups(self, message):
"""lists all the blobs in the backups bucket."""
storage_client = storage.Client.from_service_account_json(json_credentials_path=GCP_CREDS_PATH)
blobs = storage_client.list_blobs(GCP_GS_BUCKET, max_results=10)
send_str = "```"
for blob in blobs:
send_str += f"{blob.time_created} - {blob.name}\n"
send_str += "```"
await message.channel.send(send_str)
def main():
print(f"Starting up...")
admins = load_admins()
commands = Commands()
intents = discord.Intents.default()
discord_client = discord.Client(intents=intents)
print(f"Connected to Discord!")
print(f"ADMINS: {admins}")
@discord_client.event
async def on_message(message):
if message.author == discord_client.user:
return
print(f"[+] Message from: {message.author.name}")
if message.author.name not in admins:
print("[-] User not admin, skipping...")
return
print(f"[i] {message.channel} - {message.author.name} - {message.content}")
message_split = message.content.split(" ")
target_command = message_split[1]
command_func = commands.commands.get(target_command)
if command_func is not None:
await command_func(message)
else:
print(f"[-] No command found for {target_command}")
discord_client.run(DISCORD_TOKEN)
if __name__ == "__main__":
main()