Skip to content

Commit 95fa3aa

Browse files
committed
Initializing repo
0 parents  commit 95fa3aa

6 files changed

Lines changed: 202 additions & 0 deletions

File tree

.gitignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
.idea
2+
*.zip
3+
*.log
4+
.env
5+
*.pyc

DiscordRequests.py

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
import requests
2+
from requests.exceptions import HTTPError, Timeout
3+
import discord
4+
5+
6+
# Helper class to send Discord API requests
7+
class DiscordRequests:
8+
DISCORD_BASE_URL = "https://discordapp.com/api/v7"
9+
DISCORD_MESSAGE_HISTORY = "/channels/:channel_id/messages"
10+
DISCORD_CREATE_MESSAGE = "/channels/:channel_id/messages"
11+
DISCORD_EDIT_MESSAGE = "/channels/:channel_id/messages/:message_id"
12+
13+
TOKEN = None
14+
BOT_CLIENT_ID = None
15+
16+
def __init__(self, config):
17+
if 'auth_token' not in config or config['token'] is None:
18+
raise Exception('Missing Discord Token')
19+
elif 'bot_client_id' not in config or config['bot_client_id'] is None:
20+
raise Exception('Missing Bot Client ID')
21+
22+
self.TOKEN = config['token']
23+
self.BOT_CLIENT_ID = config['bot_client_id']
24+
25+
# Send a Discord API request
26+
def sendDiscordRequest(self, action, url, params=None):
27+
# Do request here
28+
29+
auth_token = f'Bot {self.TOKEN}'
30+
31+
try:
32+
if action == 'GET':
33+
response = requests.get(url, timeout=5, headers={"Authorization": auth_token})
34+
elif action == 'POST':
35+
response = requests.post(url, timeout=5, headers={"Authorization": auth_token}, json=params)
36+
elif action == 'PATCH':
37+
response = requests.patch(url, timeout=5, headers={"Authorization": auth_token}, json=params)
38+
else:
39+
raise Exception(f'Attempting to send request with unknown action: {action}')
40+
41+
response.raise_for_status()
42+
except HTTPError as http_err:
43+
print(f'HTTP error occurred for {id}: {http_err}')
44+
except Timeout as timeout:
45+
print(f'HTTP timeout occurred for {id}: {timeout}')
46+
except Exception as err:
47+
print(f'Other error occurred for {id}: {err}')
48+
else:
49+
return response.json()
50+
51+
return None
52+
53+
# Get message ID of most recent message sent by bot
54+
def getLastMessageByBot(self, channel_id):
55+
# Make request for message history
56+
# Parse message ID
57+
url = self.DISCORD_BASE_URL + self.DISCORD_MESSAGE_HISTORY.replace(':channel_id', channel_id, 1)
58+
59+
response = self.sendDiscordRequest('GET', url)
60+
61+
if response is None:
62+
return None
63+
64+
for message in response:
65+
if message["author"]["id"] != self.BOT_CLIENT_ID:
66+
continue
67+
68+
return message
69+
70+
return None
71+
72+
# Edit an existing Rich Embed message
73+
def editMessage(self, channel_id, message_id, data):
74+
# Make request to edit message
75+
url = self.DISCORD_BASE_URL + self.DISCORD_EDIT_MESSAGE.replace(':channel_id', channel_id, 1).replace(
76+
':message_id', message_id, 1)
77+
78+
response = self.sendDiscordRequest('PATCH', url, data)
79+
80+
if response is None:
81+
return None
82+
83+
return response
84+
85+
# Create a new Rich Embed message
86+
def createMessage(self, channel_id, data):
87+
# Make request to edit message
88+
url = self.DISCORD_BASE_URL + self.DISCORD_CREATE_MESSAGE.replace(':channel_id', channel_id, 1)
89+
90+
response = self.sendDiscordRequest('POST', url, data)
91+
92+
if response is None:
93+
return None
94+
95+
return response
96+
97+
# Create an initial connection to Discord to allow future messages
98+
# Only needs to be called once per Discord server
99+
def intialConnection(self):
100+
client = discord.Client()
101+
102+
@client.event
103+
async def on_ready():
104+
print('Closing connection')
105+
await client.close()
106+
return None
107+
108+
client.run(self.TOKEN)

DynamoDBHelper.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
from boto3 import resource
2+
3+
4+
class DynamoDBHelper:
5+
DB = None
6+
7+
def __init__(self, db_type, db_region):
8+
self.DB = resource(db_type, region_name=db_region)
9+
10+
def getDocument(self, table_name, key, val):
11+
table = self.DB.Table(table_name)
12+
item = table.get_item(Key={key: val})
13+
14+
if not item:
15+
return None
16+
17+
if 'Item' not in item:
18+
return None
19+
20+
return item['Item']
21+
22+
def createDocument(self, table_name, doc):
23+
table = self.DB.Table(table_name)
24+
response = table.put_item(Item=doc)
25+
26+
return response
27+
28+
def updateDocument(self, table_name, key_dict, update_expression, expression_attribute_values):
29+
table = self.DB.Table(table_name)
30+
response = table.update_item(Key=key_dict, UpdateExpression=update_expression, ExpressionAttributeValues=expression_attribute_values, ReturnValues="UPDATED_NEW")
31+
32+
return response

NitradeoRequests.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import requests
2+
from requests.exceptions import HTTPError, Timeout
3+
4+
5+
class NitradoRequests:
6+
NITRAPI_BASE_URL = "https://api.nitrado.net"
7+
NITRAPI_GAMESERVER_BOOST_HISTORY = "/services/:id/gameservers/boost/history"
8+
NITRAPI_GAMESERVER_DETAILS = "/services/:id/gameservers"
9+
10+
# Send a Discord API request
11+
def sendNitrapiRequest(self, action, token, url, params=None):
12+
# Do request here
13+
14+
auth_token = f'Bearer {token}'
15+
16+
try:
17+
if action == 'GET':
18+
response = requests.get(url, timeout=5, headers={"Authorization": auth_token})
19+
elif action == 'POST':
20+
response = requests.post(url, timeout=5, headers={"Authorization": auth_token}, json=params)
21+
elif action == 'PATCH':
22+
response = requests.patch(url, timeout=5, headers={"Authorization": auth_token}, json=params)
23+
else:
24+
raise Exception(f'Attempting to send request with unknown action: {action}')
25+
26+
response.raise_for_status()
27+
except HTTPError as http_err:
28+
print(f'HTTP error occurred for {id}: {http_err}')
29+
except Timeout as timeout:
30+
print(f'HTTP timeout occurred for {id}: {timeout}')
31+
except Exception as err:
32+
print(f'Other error occurred for {id}: {err}')
33+
else:
34+
return response.json()
35+
36+
return None
37+
38+
# Make GET request to NitrAPI for boost history
39+
# Return: Dict | None
40+
# See for more info: https://doc.nitrado.net/
41+
def getBoostHistory(self, token, gameserver_id):
42+
url = self.NITRAPI_BASE_URL + self.NITRAPI_GAMESERVER_BOOST_HISTORY.replace(':id', gameserver_id, 1)
43+
44+
return self.sendNitrapiRequest("GET", token, url)
45+
46+
# Make GET request to NitrAPI for gameserver details
47+
# Return: Dict | None
48+
# See for more info: https://doc.nitrado.net/#api-Gameserver-Details
49+
def getGameserverDetails(self, token, gameserver_id):
50+
url = self.NITRAPI_BASE_URL + self.NITRAPI_GAMESERVER_DETAILS.replace(':id', gameserver_id, 1)
51+
52+
return self.sendNitrapiRequest("GET", token, url)

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# Python modules for use in other projects

requirements.txt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
discord.py
2+
requests
3+
python-dotenv
4+
boto3

0 commit comments

Comments
 (0)