How would I get a Texture in the project and send it over to discord using a webhook? Unity - unity3d

What I am trying to do is take a texture(any texture) from unity and use a webhook from discord to send it to discord.
This is what I have so far keep in mind I started coding not long ago so I'm not very familiar with this;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class SendMessage : MonoBehaviour
{
public string Message, Subject;
public string webhook;
public Texture2D screenshot;
// Start is called before the first frame update
void Start()
{
}
IEnumerator SendWebHook(string link, string message, System.Action<bool> action)
{
WWWForm form = new WWWForm();
form.AddField("content", message + screenshot.EncodeToPNG());
using (UnityWebRequest www = UnityWebRequest.Post(link, form))
{
yield return www.SendWebRequest();
if(www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
action(false);
}
else
{
action(true);
}
}
}
public void send()
{
StartCoroutine(SendWebHook(webhook, Subject + Message, (success) =>
{
if(success)
{
Debug.Log("good");
}
}));
}
}

Related

With Photon x FMETP Asset is something that you know?

I'm trying to use the FMETP asset implementing the pun script following the information from the web page and the process that I'm doing in unity editor is object with FMETP Encoder assignig the FMStreamPun method to send the bit -> New Object with FMStreamPun script signing the FMETP Encoder.
Doing that the decoder doesn't receive the information from the encoder.
Do you know something about that topic?
This is the FMStreamPun Script
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using FMETP;
public class FMStreamPun : Photon.Pun.MonoBehaviourPun, IPunObservable
{
private Queue<byte[]> appendQueueSendData = new Queue<byte[]>();
public int appendQueueSendDataCount { get { return appendQueueSendData.Count; } }
public UnityEventByteArray OnDataByteReadyEvent = new UnityEventByteArray();
public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
Debug.Log("entro al seriaize view");
if (stream.IsWriting)
{
Debug.Log("is writting");
//Send the meta data of the byte[] queue length
stream.SendNext(appendQueueSendDataCount);
//Sending the queued byte[]
while (appendQueueSendDataCount > 0)
{
byte[] sentData = appendQueueSendData.Dequeue();
stream.SendNext(sentData);
}
}
if (stream.IsReading)
{
if (!photonView.IsMine)
{
//Get the queue length
int streamCount = (int)stream.ReceiveNext();
for (int i = 0; i < streamCount; i++)
{
//reading stream one by one
byte[] receivedData = (byte[])stream.ReceiveNext();
OnDataByteReadyEvent.Invoke(receivedData);
}
}
}
}
public void Action_SendData(byte[] inputData)
{
Debug.Log("entro al action send data");
//inputData(byte[]) is the encoded byte[] from your encoder
//doesn't require any stream, when there is only one player in the room
//if (PhotonNetwork.CurrentRoom.PlayerCount > 1)
//{
appendQueueSendData.Enqueue(inputData);
//}
}
}
I'm using both assets but I can't find any way to receive the information ito de decoder

Unity HTTP/1.1 400 Bad Request while fetching data from Mongo Atlas

I'm trying to fetch a collection with Mongo Atlas Data API. In API logs, Status seems as "OK" but i'm getting "Bad Request" error in Unity editor. Am I missing something? Thanks for helps.
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using System;
using System.Text;
public class Queries : MonoBehaviour
{
public static void DumpToConsole(object obj)
{
var output = JsonUtility.ToJson(obj);
Debug.Log(output);
}
void OnMouseDown()
{
StartCoroutine(GetDB());
IEnumerator GetDB() {
WWWForm form = new WWWForm();
form.AddField("dataSource","Cluster0");
form.AddField("database","Herbarium");
form.AddField("collection","Herbs-Specs");
/*byte [] bodyRaw = form.data;
string formInput = Convert.ToBase64String(bodyRaw);*/
UnityWebRequest www = UnityWebRequest.Post("https://data.mongodb-api.com/**********/data/v1/action/find", form);
www.SetRequestHeader("Content-Type", "application/json");
www.SetRequestHeader("Access-Control-Request-Headers", "*");
www.SetRequestHeader("api-key", "***********");
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log(www.error);
}
else
{
DumpToConsole(www.downloadHandler.text);
}
}
}
}

photon pun2 unity playfab email and password auth

i want to make email auth with playfab and photon istead of custom id auth shown in photon quickstart guide playfab. i tried this script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Realtime;
using Photon.Pun;
using PlayFab;
using PlayFab.ClientModels;
using TMPro;
public class pfauth : MonoBehaviour
{
#region objects
[Header (" register ")]
public TMP_InputField user;
public TMP_InputField email;
public TMP_InputField pass;
public GameObject regpanel;
[Header(" login ")]
public TMP_InputField luser;
public TMP_InputField lpass;
public GameObject loginpanel;
[Header(" Other gameobjects ")]
public TMP_Text message;
public bool IsAuthenticated = false;
public GameObject prpo;
public float sec;
private string _playFabPlayerIdCache;
LoginWithPlayFabRequest loginrequest;
#endregion
public void Start() //set the loginpanel as disable at start
{
loginpanel.SetActive(false);
regpanel.SetActive(true);
}
public void login()
{
loginrequest = new LoginWithPlayFabRequest();
loginrequest.Username = luser.text;
loginrequest.Password = lpass.text;
PlayFabClientAPI.LoginWithPlayFab(loginrequest, \\in this line how can i call requestphotontoken result => {
//if account found
message.text = "welcome back" + user.text + "loging in...";
StartCoroutine("waitforempty"); //hide the text after few seconds
IsAuthenticated = true;
Debug.Log("logged in");
}, error => {
message.text = "Sorry! Failed to login(" + error.ErrorMessage + ")";
StartCoroutine("waitforempty"); //hide the text after few seconds
Debug.Log(error.ErrorDetails);
IsAuthenticated = false;
}, null);
}
public void register()
{
RegisterPlayFabUserRequest request = new RegisterPlayFabUserRequest();
request.Email = email.text;
request.Password = pass.text;
request.Username = user.text;
PlayFabClientAPI.RegisterPlayFabUser(request, \\in this line how can i call requestphotontoken result =>
{
message.text = "Your account has been created!";
StartCoroutine("waitforempty"); //hide the text after few seconds
prpo.SetActive(true);
}, error =>
{
message.text = "Sorry! Failed to create your account(" + error.ErrorMessage + ")";
StartCoroutine("waitforempty"); //hide the text after few seconds
});
}
public void regpan()
{
loginpanel.SetActive(false);
regpanel.SetActive(true);
}
public void logbak()
{
loginpanel.SetActive(true);
regpanel.SetActive(false);
}
IEnumerator waitforempty() //hide the text after few seconds
{
yield return new WaitForSeconds(sec);
message.text = " ";
}
private void RequestPhotonToken(LoginResult obj)
{
LogMessage("PlayFab authenticated. Requesting photon token...");
//We can player PlayFabId. This will come in handy during next step
_playFabPlayerIdCache = obj.PlayFabId;
PlayFabClientAPI.GetPhotonAuthenticationToken(new GetPhotonAuthenticationTokenRequest()
{
PhotonApplicationId = PhotonNetwork.PhotonServerSettings.AppSettings.AppIdRealtime
}, AuthenticateWithPhoton, OnPlayFabError);
}
/*
* Step 3
* This is the final and the simplest step. We create new AuthenticationValues instance.
* This class describes how to authenticate a players inside Photon environment.
*/
private void AuthenticateWithPhoton(GetPhotonAuthenticationTokenResult obj)
{
LogMessage("Photon token acquired: " + obj.PhotonCustomAuthenticationToken + " Authentication complete.");
//We set AuthType to custom, meaning we bring our own, PlayFab authentication procedure.
var customAuth = new AuthenticationValues { AuthType = CustomAuthenticationType.Custom };
//We add "username" parameter. Do not let it confuse you: PlayFab is expecting this parameter to contain player PlayFab ID (!) and not username.
customAuth.AddAuthParameter("username", _playFabPlayerIdCache); // expected by PlayFab custom auth service
//We add "token" parameter. PlayFab expects it to contain Photon Authentication Token issues to your during previous step.
customAuth.AddAuthParameter("token", "");
//We finally tell Photon to use this authentication parameters throughout the entire application.
PhotonNetwork.AuthValues = customAuth;
Debug.Log(PhotonNetwork.ConnectUsingSettings().ToString());
}
private void OnPlayFabError(PlayFabError obj)
{
LogMessage(obj.GenerateErrorReport());
}
public void LogMessage(string message)
{
Debug.Log("PlayFab + Photon Example: " + message);
}
}
but in the "PlayFabClientAPI.LoginWithPlayFab(loginrequest, \in this line how can i call requestphotontoken" result line in both login and register void when i try to call RequestPhotonToken i shows this error-
Cannot convert methord group to function
please help
Photon PUN 2
Playfab latest

POST requests to Flask from Unity result in `null` values

After getting this demo server working I am able return GET requests from it to Unity, but when I would try to send data from Unity to the local server using POST requests it would only show null values added into the server. This is the code I was using in Unity:
IEnumerator Upload()
{
WWWForm form = new WWWForm();
form.AddField("charge","+4/3");
form.AddField("name", "doubletop");
using (UnityWebRequest www = UnityWebRequest.Post("http://localhost:5000/quarks/", form))
{
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Form upload complete!");
}
}
}
I would get "Form upload complete!" in the console, and GET requests would work, but those null values kept coming.
I modified my Upload() method to the PostRequest() in this example, and now it works!
Here's the full code:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class HTTP : MonoBehaviour
{
void Start()
{
// A correct website page.
StartCoroutine(GetRequest("localhost:5000/quarks"));
PostData();
StartCoroutine(GetRequest("localhost:5000/quarks"));
// A non-existing page.
//StartCoroutine(GetRequest("https://error.html"));
}
IEnumerator GetRequest(string uri)
{
using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
{
// Request and wait for the desired page.
yield return webRequest.SendWebRequest();
string[] pages = uri.Split('/');
int page = pages.Length - 1;
if (webRequest.isNetworkError)
{
Debug.Log(pages[page] + ": Error: " + webRequest.error);
}
else
{
Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text);
}
}
}
[Serializable]
public class Quark
{
public string name;
public string charge;
}
public void PostData()
{
Quark gamer = new Quark();
gamer.name = "doublebottom";
gamer.charge = "4/3";
string json = JsonUtility.ToJson(gamer);
StartCoroutine(PostRequest("http://localhost:5000/quarks", json));
}
IEnumerator PostRequest(string url, string json)
{
var uwr = new UnityWebRequest(url, "POST");
byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(json);
uwr.uploadHandler = (UploadHandler)new UploadHandlerRaw(jsonToSend);
uwr.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
uwr.SetRequestHeader("Content-Type", "application/json");
//Send the request then wait here until it returns
yield return uwr.SendWebRequest();
if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
Debug.Log("Received: " + uwr.downloadHandler.text);
}
}
}

Unity3D IP Camera

I'm using a Marmitek IP RoboCam 641 to import a video feed into unity. I use constantly refreshing snapshots to update a GUI.DrawTexture on the screen. However I recently switched to the Marmitek from a Velleman wireless ip colour camera. Now my snapshot only refreshes once or twice, before stopping and giving this error:
UnityException: Recv failure: Connection was reset
SEMTEX+c__Iterator0.MoveNext () (at Assets/Scripts/SEMTEX.cs:37)
And this is my code:
using UnityEngine;
using System.Collections;
public class SEMTEX : MonoBehaviour {
//public string uri = "http://192.168.1.101/snapshot.cgi";//velleman
public string uri = "http://192.168.1.30/cgi/jpg/image.cgi";//marmitek
public string username = "admin";
public string password = "admin";
int calc = 0;
Texture2D cam;
Texture2D cam2;
public void Start() {
cam=new Texture2D(1, 1, TextureFormat.RGB24, true);
StartCoroutine(Fetch());
cam2=new Texture2D(1, 1, TextureFormat.RGB24, true);
StartCoroutine(Fetch());
}
public IEnumerator Fetch() {
while(true) {
Debug.Log("fetching... "+Time.realtimeSinceStartup);
WWWForm form = new WWWForm();
form.AddField("dummy", "field"); // required by WWWForm
WWW www = new WWW(uri, form.data, new System.Collections.Generic.Dictionary<string,string>() { // using www.headers is depreciated by some odd reason
{"Authorization", "Basic " + System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(username+":"+password))}
});
yield return www;
if(!string.IsNullOrEmpty(www.error))
throw new UnityException(www.error);
www.LoadImageIntoTexture(cam);
www.LoadImageIntoTexture(cam2);
}
}
public void OnGUI() {
GUI.DrawTexture(new Rect(0,0,Screen.width/2,Screen.height), cam);
calc = (Screen.width/2-100);
GUI.DrawTexture(new Rect(calc,0,Screen.width/2,Screen.height), cam2);
Debug.Log (Screen.width);
}
Does anyone have any ideas regarding my error?