1+ using JetBrains . Annotations ;
2+ using MEC ;
3+ using Newtonsoft . Json . Linq ;
4+ using SER . Code . ArgumentSystem . Arguments ;
5+ using SER . Code . ArgumentSystem . BaseArguments ;
6+ using SER . Code . Helpers . Exceptions ;
7+ using SER . Code . MethodSystem . BaseMethods . Synchronous ;
8+ using SER . Code . MethodSystem . BaseMethods . Yielding ;
9+ using SER . Code . MethodSystem . MethodDescriptors ;
10+ using SER . Code . MethodSystem . Methods . HTTPMethods ;
11+ using SER . Code . ValueSystem ;
12+ using UnityEngine . Networking ;
13+
14+ namespace SER . Code . MethodSystem . Methods . DiscordMethods ;
15+
16+ [ UsedImplicitly ]
17+ public class SendDiscordMessageAndWaitMethod : YieldingReturningMethod < TextValue > , ICanError
18+ {
19+ public override string Description =>
20+ "Sends a message using a discord webhook and waits until it is completed. Returns the message id." ;
21+
22+ public string [ ] ErrorReasons =>
23+ [
24+ ..HTTPPostMethod . HttpErrorReasons ,
25+ "Provided URL is not a valid webhook URL."
26+ ] ;
27+
28+ public override Argument [ ] ExpectedArguments { get ; } =
29+ [
30+ new TextArgument ( "webhook url" ) ,
31+ new ReferenceArgument < DiscordMessageMethod . DMessage > ( "message object" )
32+ ] ;
33+
34+ public override IEnumerator < float > Execute ( )
35+ {
36+ var webhookUrl = Args . GetText ( "webhook url" ) ;
37+ var messageObject = Args . GetReference < DiscordMessageMethod . DMessage > ( "message object" ) ;
38+
39+ if ( ! webhookUrl . StartsWith ( "https://discord.com/api/webhooks/" ) )
40+ throw new ScriptRuntimeError ( this , ErrorReasons . Last ( ) ) ;
41+
42+ using UnityWebRequest request = new UnityWebRequest ( webhookUrl + "?wait=true" , "POST" ) ;
43+ byte [ ] bodyRaw = System . Text . Encoding . UTF8 . GetBytes ( messageObject . ToString ( ) ) ;
44+ request . uploadHandler = new UploadHandlerRaw ( bodyRaw ) ;
45+ request . downloadHandler = new DownloadHandlerBuffer ( ) ;
46+ request . SetRequestHeader ( "Content-Type" , "application/json" ) ;
47+
48+ yield return Timing . WaitUntilDone ( request . SendWebRequest ( ) ) ;
49+
50+ if ( request . error is { } error )
51+ {
52+ throw new ScriptRuntimeError (
53+ this ,
54+ $ "Address { webhookUrl } has returned an error: { error } "
55+ ) ;
56+ }
57+
58+ try
59+ {
60+ ReturnValue = JObject . Parse ( request . downloadHandler . text ) [ "id" ] ? . Value < string > ( )
61+ ?? throw new Exception ( ) ;
62+ }
63+ catch
64+ {
65+ throw new ScriptRuntimeError ( this , "Returned message object from discord is invalid." ) ;
66+ }
67+ }
68+ }
0 commit comments