Skip to content

Commit

Permalink
Moved API-related error handling to Discord interactions origin
Browse files Browse the repository at this point in the history
  • Loading branch information
dssecret committed Dec 27, 2023
1 parent e7fcc53 commit 51f2e81
Show file tree
Hide file tree
Showing 11 changed files with 327 additions and 587 deletions.
114 changes: 97 additions & 17 deletions skynet/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,17 @@
# along with this program. If not, see <https://www.gnu.org/licenses/>.

import logging
from functools import wraps

from flask import Blueprint, abort, jsonify, request
from nacl.exceptions import BadSignatureError
from tornium_commons.skyutils import SKYNET_INFO
from tornium_commons.errors import (
DiscordError,
MissingKeyError,
NetworkingError,
TornError,
)
from tornium_commons.skyutils import SKYNET_ERROR

import skynet.commands
import skynet.skyutils
Expand All @@ -39,21 +46,6 @@
mod = Blueprint("botinteractions", __name__)


def in_dev_command(interaction, *args, **kwargs):
return {
"type": 4,
"data": {
"embeds": [
{
"title": "Command In Development",
"description": "This command is not yet ready for production use.",
"color": SKYNET_INFO,
}
]
},
}


_autocomplete = {"notify": skynet.commands.notify.notify_autocomplete_switchboard}
_buttons = {
"faction:vault:cancel": skynet.commands.faction.cancel.cancel_button,
Expand Down Expand Up @@ -101,7 +93,81 @@ def in_dev_command(interaction, *args, **kwargs):
_buttons[button["custom_id"]] = button["function"]


def handle_interaction_errors(f):
@wraps
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
except NetworkingError as e:
return jsonify(
{
"type": 4,
"data": {
"embeds": [
{
"title": "Networking Error",
"description": f"A networking error has occurred on an API call resulting in HTTP f{e.code}: {e.message}",
"color": SKYNET_ERROR,
},
],
"flags": 64,
},
}
)
except TornError as e:
return jsonify(
{
"type": 4,
"data": {
"embeds": [
{
"title": "Torn API Error",
"description": f"An error has occurred on a Torn API call resulting in error code f{e.code}: {e.message}",
"color": SKYNET_ERROR,
},
],
"flags": 64,
},
}
)
except MissingKeyError:
return jsonify(
{
"type": 4,
"data": {
"embeds": [
{
"title": "Missing API Key",
"description": "There wasn't an API key available for a Torn API call.",
"color": SKYNET_ERROR,
},
],
"flags": 64,
},
}
)
except DiscordError as e:
return jsonify(
{
"type": 4,
"data": {
"embeds": [
{
"title": "Discord API Error",
"description": f"A Discord API error has occurred resulting in an error f{e.code}: {e.message}",
"color": SKYNET_ERROR,
},
],
"flags": 64,
},
}
)

return wrapper


@mod.route("/skynet", methods=["POST"])
@handle_interaction_errors
def skynet_interactions():
try: # https://discord.com/developers/docs/interactions/receiving-and-responding#security-and-authorization
skynet.skyutils.verify_headers(request)
Expand Down Expand Up @@ -166,4 +232,18 @@ def skynet_interactions():
_autocomplete[request.json["data"]["name"]](request.json, invoker=invoker, admin_keys=admin_keys)
)

return jsonify(in_dev_command(request.json))
return jsonify(
{
"type": 4,
"data": {
"embeds": [
{
"title": "Unknown Interaction",
"description": "This interaction did not match any implemented slash commands or button interactions.",
"color": SKYNET_ERROR,
}
],
"flags": 64,
},
}
)
123 changes: 26 additions & 97 deletions skynet/commands/bot/verify.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
from peewee import DoesNotExist
from tornium_celery.tasks.api import discordget, discordpatch
from tornium_celery.tasks.user import update_user
from tornium_commons.errors import DiscordError, MissingKeyError, NetworkingError
from tornium_commons.errors import TornError
from tornium_commons.formatters import find_list
from tornium_commons.models import Faction, Server, User
from tornium_commons.skyutils import SKYNET_ERROR, SKYNET_GOOD, SKYNET_INFO
Expand Down Expand Up @@ -129,37 +129,7 @@ def verify(interaction, *args, **kwargs):
update_user_kwargs["discordid"] = user.discord_id

if member != -1:
try:
discord_member = discordget(f"guilds/{guild.sid}/members/{update_user_kwargs['discordid']}")
except DiscordError as e:
return {
"type": 4,
"data": {
"embeds": [
{
"title": "Discord API Error",
"description": f'The Discord API has raised error code {e.code}: "{e.message}".',
"color": SKYNET_ERROR,
}
],
"flags": 64,
},
}
except NetworkingError as e:
return {
"type": 4,
"data": {
"embeds": [
{
"title": "HTTP Error",
"description": f'The Torn API has returned an HTTP error {e.code}: "{e.message}".',
"color": SKYNET_ERROR,
}
],
"flags": 64,
},
}

discord_member = discordget(f"guilds/{guild.sid}/members/{update_user_kwargs['discordid']}")
user_roles = discord_member["roles"]

if discord_member.get("nick") in (None, ""):
Expand Down Expand Up @@ -192,37 +162,26 @@ def verify(interaction, *args, **kwargs):

try:
update_user(**update_user_kwargs) # TODO: Handle Torn and Network errors
except MissingKeyError:
return {
"type": 4,
"data": {
"embeds": [
{
"title": "No API Key Available",
"description": "No Torn API key could be utilized for this request.",
"color": SKYNET_ERROR,
}
],
"flags": 64,
},
}
except Exception:
return {
"type": 4,
"data": {
"embeds": [
{
"title": "Verification Failed",
"description": "API call failed. Please verify that you are officially verified by Torn. "
"Otherwise, try forcing the verification. To verify on Torn, you can match your Discord and "
"Torn accounts through the [official Torn Discord server](https://www.torn.com/discord) or "
"through a [direct OAuth link](https://discordapp.com/api/oauth2/authorize?client_id=441210177971159041&redirect_uri=https%3A%2F%2Fwww.torn.com%2Fdiscord.php&response_type=code&scope=identify).",
"color": SKYNET_ERROR,
}
],
"flags": 64,
},
}
except TornError as e:
if e.code == 6:
return {
"type": 4,
"data": {
"embeds": [
{
"title": "Verification Failed",
"description": "API call failed. Please verify that you are officially verified by Torn. "
"Otherwise, try forcing the verification. To verify on Torn, you can match your Discord and "
"Torn accounts through the [official Torn Discord server](https://www.torn.com/discord) or "
"through a [direct OAuth link](https://discordapp.com/api/oauth2/authorize?client_id=441210177971159041&redirect_uri=https%3A%2F%2Fwww.torn.com%2Fdiscord.php&response_type=code&scope=identify).",
"color": SKYNET_ERROR,
}
],
"flags": 64,
},
}

raise e

try:
user: User = User.get(User.discord_id == update_user_kwargs["discordid"])
Expand All @@ -241,7 +200,6 @@ def verify(interaction, *args, **kwargs):
},
}

# TODO: Is this necessary?
if user.discord_id in (0, None):
return {
"type": 4,
Expand Down Expand Up @@ -370,39 +328,10 @@ def verify(interaction, *args, **kwargs):
if "roles" in patch_json:
patch_json["roles"] = list(set(patch_json["roles"]))

try:
discordpatch(
f"guilds/{guild.sid}/members/{user.discord_id}",
patch_json,
)
except DiscordError as e:
return {
"type": 4,
"data": {
"embeds": [
{
"title": "Discord API Error",
"description": f'The Discord API has raised error code {e.code}: "{e.message}".',
"color": 0xC83F49,
}
],
"flags": 64,
},
}
except NetworkingError as e:
return {
"type": 4,
"data": {
"embeds": [
{
"title": "HTTP Error",
"description": f'The Torn API has returned an HTTP error {e.code}: "{e.message}".',
"color": 0xC83F49,
}
],
"flags": 64,
},
}
discordpatch(
f"guilds/{guild.sid}/members/{user.discord_id}",
patch_json,
)

if user.faction is None:
faction_str = "None"
Expand Down
7 changes: 1 addition & 6 deletions skynet/commands/faction/assist.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,12 +297,7 @@ def assist(interaction, *args, **kwargs):
# ],
# }
#
# try:
# discordpost(f"channels/{server.assistschannel}/messages", payload=data, channel=server.assistschannel)
# except DiscordError:
# continue
# except NetworkingError:
# continue
# discordpost(f"channels/{server.assistschannel}/messages", payload=data, channel=server.assistschannel)
#
# servers_forwarded.append(server)
#
Expand Down
34 changes: 1 addition & 33 deletions skynet/commands/faction/balance.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@

from peewee import DoesNotExist
from tornium_celery.tasks.api import tornget
from tornium_commons.errors import NetworkingError, TornError
from tornium_commons.formatters import commas, find_list
from tornium_commons.models import User
from tornium_commons.skyutils import SKYNET_ERROR, SKYNET_GOOD
Expand Down Expand Up @@ -115,38 +114,7 @@ def balance(interaction, *args, **kwargs):
},
}

try:
faction_balances = tornget("faction/?selections=donations", random.choice(aa_keys))
except TornError as e:
return {
"type": 4,
"data": {
"embeds": [
{
"title": "Torn API Error",
"description": f'The Torn API has raised error code {e.code}: "{e.message}".',
"color": SKYNET_ERROR,
}
],
"flags": 64,
},
}
except NetworkingError as e:
return {
"type": 4,
"data": {
"embeds": [
{
"title": "HTTP Error",
"description": f'The Torn API has returned an HTTP error {e.code}: "{e.message}".',
"color": SKYNET_ERROR,
}
],
"flags": 64,
},
}

faction_balances = faction_balances["donations"]
faction_balances = tornget("faction/?selections=donations", random.choice(aa_keys))["donations"]

if str(user.tid) not in faction_balances:
return {
Expand Down
Loading

0 comments on commit 51f2e81

Please sign in to comment.