|
| 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) |
0 commit comments