Does anyone know how i would send all the data from the user to a discord webhook message?
So my code is like so:
private void materialSingleLineTextField1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
userName = materialSingleLineTextField1.Text;
rapcount(userName);
materialLabel2.Text = "Username: " + materialSingleLineTextField1.Text;
var client = new WebClient();
var text = client.DownloadString("https://api.roblox.com/users/get-by-username?username=" + materialSingleLineTextField1.Text);
Post post = JsonConvert.DeserializeObject<Post>(text);
Id = post.Id;
materialLabel3.Text = "ID: " + post.Id;
materialLabel4.Text = "Online: " + post.IsOnline;
var request = WebRequest.Create("https://www.roblox.com/headshot-thumbnail/image?userId=" + Id + "&width=420&height=420&format=png");
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
pictureBox1.Image = Bitmap.FromStream(stream);
}
//https://discordapp.com/api/webhooks/450790622446485525/HW8nYfZ39J0VPKDcxEuLoYpwVbBt8qxF4uM1SMJGp8WXIlZ33jlqzSvMThM7rSoxJUJU
materialSingleLineTextField1.Text = "";
}
}
and I want the username and ID sent as a message. Please help <3
Uhm i just got this from someone else
class
Link
code
using (dWebHook dcWeb = new dWebHook())
{
dcWeb.ProfilePicture = "https://static.giantbomb.com/uploads/original/4/42381/1196379-gas_mask_respirator.jpg";
dcWeb.UserName = "Bot";
dcWeb.WebHook = webHook;
dcWeb.SendMessage("Hello");
}
I know this thread is getting pretty old and dated but being the first result on Google as of right now, I felt posting my version and my preferred way of doing this, considering it took me a while to figure out.
Make sure to add a reference to System.Net.
using System.Net;
Method for keeping same webhook:
static void SendMs(string message)
{
string webhook = "WEBHOOK_HERE";
WebClient client = new WebClient();
client.Headers.Add("Content-Type", "application/json");
string payload = "{\"content\": \"" + message + "\"}";
client.UploadData(webhook, Encoding.UTF8.GetBytes(payload));
}
Using this method:
SendMs("Hello, world!");
Method for changing webhook on call:
static void SendMs(string message, string webhook)
{
WebClient client = new WebClient();
client.Headers.Add("Content-Type", "application/json");
string payload = "{\"content\": \"" + message + "\"}";
client.UploadData(whurl, Encoding.UTF8.GetBytes(payload));
}
Using this method:
SendMs("Hello, world!", "https://discord.com/api/webhooks/...");
Hope this helps somebody out!
Related
I'm using Xamarin C# and php to create a simple android app that sends coordinate data to an apache sql database. When I use httpwebrequest to send a POST request to the server php, it sends a GET instead. Even though I set the request type to POST. The strange thing is that other requests that I have used using the exact same code work okay, this one specifically isn't working.
public class gpsGetterScript{
public static double longitude;
public static double latitude;
public static SimpleLocationManager locationManager = new SimpleLocationManager();
public static void startGetLocation()
{
Timer timer = new Timer();
timer.Interval = 6 * 1000;
void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
double lon = locationManager.LastLocation.Longitude;
double lat = locationManager.LastLocation.Latitude;
longitude = lon;
latitude = lat;
Console.WriteLine(lon.ToString());
Console.WriteLine(lat.ToString());
Dictionary<string, string> gpsData = new Dictionary<string, string>();
gpsData.Add("longitude", lon.ToString());
gpsData.Add("latitude", lat.ToString());
gpsData.Add("device_owner", "Test");
var url = "theURL";
var httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "POST";
var contentType = "application/json";
//var contentType = "application/x-www-form-urlencoded";
httpRequest.ContentType = contentType;
var data = JsonConvert.SerializeObject(gpsData);
//var data = "longitude=" + lon.ToString() + "&latitude=" + lat.ToString() + "&device_owner=" + "Test";
using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
{
Console.WriteLine(data.ToString());
Console.WriteLine(httpRequest.RequestUri.ToString());
Console.WriteLine(httpRequest.Headers);
Console.WriteLine(httpRequest.Method);
streamWriter.Write(data);
}
var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
}
}
timer.Elapsed += Timer_Elapsed;
timer.AutoReset = true;
timer.Start();
locationManager.StartLocationUpdates(LocationAccuracy.Balanced, 5, TimeSpan.FromMinutes(.5), TimeSpan.FromSeconds(20));
SimpleLocationLogger.Enabled = true;
}
}
here is one of the httprequests from a related project that does work (same server being used)
public static string sendLoginRequest(string email, string password)
{
var url = "theURL";
var httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
var data = "email=" + email + "&password=" + password;
using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
{
streamWriter.Write(data);
}
var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return result;
}
}
I know it is the app sending the wrong request, as when I made the php echo the request type it came back as GET. Strangely, when I use reqbin to make the POST request using the same URL, it works fine. It really is just for some reason the request in C# is not sending a POST. The other question about this was resolved by adding a www. to the api url, but that did not work for me.
UPDATE: 4/20/2022- Here is the php code
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
include_once '../../../Database.php';
include_once '../location_obj.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$database = new Database();
$db = $database->getConnection();
$data = json_decode(file_get_contents("php://input"));
$item = new location_obj($db);
$stmt = $item->InputCoordinates();
$item->longitude = $data->longitude;
$item->latitude = $data->latitude;
$item->device_owner = $data->device_owner;
if ($item->InputCoordinates()) {
echo json_encode(array("message" => "Successfully", "data" => $item, "Request Type" => $_SERVER['REQUEST_METHOD']));
}
else {
echo json_encode(array("error" => "failed! Check your data and try again.", "data" => $item, "Request Type" => $_SERVER['REQUEST_METHOD']));
}
}
else {
echo json_encode(array("error" => "Only the POST method is supported!", "Request Type" => $_SERVER['REQUEST_METHOD']));
}
?>`
I get the error {"error":"Only the POST method is supported!","Request Type":"GET"} but when I use reqbin I get "message": "Successfully", "data": { "longitude": "theLongitude", "latitude": "theLatitude", "device_owner": "Test" }, "Request Type": "POST"
I checked the url that is used using Console.WriteLine(url); , it is the right one.
I fixed it, seems I forgot to add a / at the end of the URL. It was https://example.com/api/v2/location/input instead of https://example.com/api/v2/location/input/
I have a Huawei b525-23a router. Using it's web interface you can send/check SMS but I want to do it automatically from an C# app. I didn't found any API documentation for it so any link will be very good.
I managed to find some HTTPRequests using Chrome but when I use it from C# I get the 125003 error that is according to some google search an authentication problem.
Here are some parts of my code :
private void button4_Click(object sender, EventArgs e)
{
// getting SenInfo and TokInfo
string urlTokenInfo = "http://192.168.8.1/api/webserver/SesTokInfo";
HttpWebRequest requestTokenInfo = (HttpWebRequest)WebRequest.Create(urlTokenInfo);
requestTokenInfo.Method = "GET";
WebResponse responseTokenInfo = requestTokenInfo.GetResponse();
Stream responseTokenInfoStream = responseTokenInfo.GetResponseStream();
string responseTokenInfoString = new StreamReader(responseTokenInfoStream).ReadToEnd();
var rootElement = XElement.Parse(responseTokenInfoString);
string sessionId = rootElement.Element("SesInfo").Value;
string tokenInfo = rootElement.Element("TokInfo").Value;
//_________________________________________________________________________________
// trying to log
String urlLogin = "http://192.168.8.1/api/user/login";
HttpWebRequest requestLogin = (HttpWebRequest)WebRequest.Create(urlLogin);
requestLogin.Method = "POST";
String XMLLogin;
String base64Passwd = Base64Encode(passwd); //function for base64 encode
XMLLogin = " <request ><Username> " + userName + " </Username><Password> " + base64Passwd + " </Password></request> ";
byte[] requestInFormOfBytes = System.Text.Encoding.ASCII.GetBytes(XMLLogin);
requestLogin.ContentType = "text/xml;charset=utf-8";
requestLogin.ContentLength = requestInFormOfBytes.Length;
Stream requestStream = requestLogin.GetRequestStream();
requestStream.Write(requestInFormOfBytes, 0, requestInFormOfBytes.Length);
requestLogin.Headers.Add("__RequestVerificationToken", tokenInfo);
requestLogin.Headers.Add("Cookie", sessionId);
WebResponse raspuns = (HttpWebResponse)requestLogin.GetResponse();
Stream responseStreamLogin = raspuns.GetResponseStream();
string responseStrlogin = new StreamReader(responseStreamLogin).ReadToEnd();
}
}
The response that I get is
<?xml version="1.0" encoding="UTF-8"?><error><message></message><code>125003</code></error>
Thank you for your time reading this and any response will be apreciated.
Mihai Stanciu
125003 error means token verification failed.
Check the session and token values in the first html resource request file
EDIT: My original issue was related a firewall issue, now my issue is in my authorization. With both methods below I receive and "Unauthorized" response.
I'm trying to create a method that will allow me to post a status update to twitter. I'm trying to use in my application so that I can know when certain events are taking place throughout the day without having to monitor the logs, so I thought this would be a cool way to push notifications out. Only other option I could think of is email notifications but wanted to try something different (open to any other ideas of push notifications)
I've been struggling the majority of the day to try and get this code to work. Most of the examples and questions about this I've been reviewing are quite old. Below is the code I'm running.
The Response.StatusCode = 0 and the Response.Content is blank, and I can't figure out what I'm doing wrong here.
No exception is thrown, so the response must be getting executed, but does not return anything.
I've followed the guide here on creating the signature.
https://developer.twitter.com/en/docs/basics/authentication/oauth-1-0a/creating-a-signature
Any feedback would be welcome, I wondering if there is anything obvious that I'm doing wrong.
Once I have the solution to this I'm hoping to share it out, once its cleaned up with much more comments.
Using the Code Below
Tweet t = new Tweet();
t.TestTweet();
Additional NameSpaces
using RestSharp;
using System.Security.Cryptography;
Class
class Tweet
{
private string myFirstMessage = "First Message Using RestSharp";
private const string baseTwitterURL = "https://api.twitter.com/1.1/statuses/update.json";
//Keys in Alphabetical Order
private string oauth_consumer_key = GlobalVariables.ConsumerKey;
private string oauth_nonce = "abcd";
private string oauth_signature;
private string oauth_signature_method = "HMAC-SHA1";
private string oauth_timestamp;
private string oauth_token = GlobalVariables.Token;
private string oauth_version = "1.0";
private string ConsumerKeySecret = GlobalVariables.ConsumerKeySecret;
private string AccessTokenSecret = GlobalVariables.AccessTokenSecret;
public Tweet()
{
DateTime epochUtc = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var timestamp = (int)((DateTime.UtcNow - epochUtc).TotalSeconds);
oauth_timestamp = timestamp.ToString();
}
public void TestTweet()
{
string fullURL = baseTwitterURL + Uri.EscapeDataString(myFirstMessage);
var client = new RestClient(fullURL);
var request = new RestRequest(Method.POST);
string parameterString = GenerateParameterString(oauth_consumer_key, oauth_nonce, oauth_signature_method, oauth_timestamp, oauth_token, oauth_version);
string signatureBaseString = GenerateSignatureBaseString(parameterString);
string signingKey = GenerateSigningKey();
HMACSHA1 mySignature = new HMACSHA1();
oauth_signature = Convert.ToBase64String(mySignature.ComputeHash(new ASCIIEncoding().GetBytes(string.Format("{0}&{1}", signatureBaseString, signingKey))));
request.AddHeader("authorization", "OAuth");
request.AddParameter("oauth_consumer_key", oauth_consumer_key);
request.AddParameter("oauth_nonce", oauth_nonce);
request.AddParameter("oauth_signature", oauth_signature);
request.AddParameter("oauth_signature_method", oauth_signature_method);
request.AddParameter("oauth_timestamp", oauth_timestamp);
request.AddParameter("oauth_token", oauth_token);
request.AddParameter("oauth_version", oauth_version);
string requestString = string.Join(",", request.Parameters.ToList());
try
{
Console.WriteLine("Attemping to send response" + "\n");
IRestResponse response = client.Execute(request);
}
catch (Exception Ex)
{
Console.WriteLine("Exception Ex.Message: " + Ex.Message);
Console.WriteLine("Exception Ex.ToString: " + Ex.ToString());
}
}
public string GenerateParameterString(
string oauth_consumer_key,
string oauth_nonce,
string oauth_signature_method,
string oauth_timestamp,
string oauth_token,
string oauth_version)
{
StringBuilder parameterString = new StringBuilder();
parameterString.Append("include_entities=true&");
parameterString.Append("oauth_consumer_key=" + Uri.EscapeDataString(oauth_consumer_key) + "&");
parameterString.Append("oauth_nonce=" + Uri.EscapeDataString(oauth_nonce) + "&");
parameterString.Append("oauth_signature_method=" + Uri.EscapeDataString(oauth_signature_method) + "&");
parameterString.Append("oauth_timestamp=" + Uri.EscapeDataString(oauth_timestamp) + "&");
parameterString.Append("oauth_token=" + Uri.EscapeDataString(oauth_token) + "&");
parameterString.Append("oauth_version=" + Uri.EscapeDataString(oauth_version) + "&");
parameterString.Append("status=" + Uri.EscapeDataString(myFirstMessage));
return parameterString.ToString();
}
public string GenerateSignatureBaseString(string parameterString)
{
StringBuilder SignatureBaseString = new StringBuilder();
SignatureBaseString.Append("POST&");
SignatureBaseString.Append(Uri.EscapeDataString(baseTwitterURL));
SignatureBaseString.Append("&");
SignatureBaseString.Append(Uri.EscapeDataString(parameterString));
return SignatureBaseString.ToString();
}
public string GenerateSigningKey()
{
StringBuilder SigningKey = new StringBuilder();
SigningKey.Append(Uri.EscapeDataString(ConsumerKeySecret));
SigningKey.Append("&");
SigningKey.Append(Uri.EscapeDataString(AccessTokenSecret));
return SigningKey.ToString();
}
}
Edited: RestSharp OAuth1Authenticator Method
public void TestTweetWithAuthenticator()
{
string fullURL = baseTwitterURL;
var client = new RestClient(fullURL)
{
Authenticator = OAuth1Authenticator.ForProtectedResource(oauth_consumer_key, ConsumerKeySecret, oauth_token, AccessTokenSecret)
};
var request = new RestRequest(Method.POST);
request.AddParameter("status", Uri.EscapeDataString(myFirstMessage));
try
{
Console.WriteLine("Attemping to send response" + "\n");
IRestResponse response = client.Execute(request);
}
catch (Exception Ex)
{
}
}
I am completely new to this kind of programming so I don't really know if there is an answer to this already, but I weren't able to find it. So I am testing to see if I can get a dry-run gcm message to work without errors.
The error I get is the error 400 Invalid Request, and it's saying something about the json being invalid, so I have assumed the problem has to do with string manipulation or the definition of postdata, but I can't figure it out. Most of the code is just copy pasted anyway so one could believe that others in a similar situation will get the same error, if they copy from the same source.
And also I have put in actual values for the "lorem"s.
This is the only code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;
namespace ServerGMC
{
public class ServerGMC
{
static void Main ()
{
// Prepares and calls the function to send message
List<string> RedIdList = new List<string>(1) { "aaaaaaaaaaaaaaaaaaaaaaaa" };
RedIdList.TrimExcess();
Console.WriteLine(SendNotification(RedIdList, "HelloWorld", "test", 220299));
Console.Read();
}
static public string SendNotification(List<string> deviceRegIds, string message, string title, long id)
{
try
{
string regIds = string.Join("\",\"", deviceRegIds);
string AppId = "lorem";
var SenderId = "lorem";
NotificationMessage nm = new NotificationMessage();
nm.Title = title;
nm.Message = message;
nm.ItemId = id;
var value = new JavaScriptSerializer().Serialize(nm);
WebRequest wRequest;
wRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
wRequest.Method = "post";
wRequest.ContentType = " application/json;charset=UTF-8";
wRequest.Headers.Add(string.Format("Authorization: key={0}", AppId));
wRequest.Headers.Add(string.Format("Sender: id={0}", SenderId));
string postData = "{\"collapse_key\":\"standard\",\"time_to_live\":108,\"delay_while_idle\":true,\"dry_run\":true,\"data\": { \"message\" : " + "\"" + value + "\",\"time\": " + "\"" + System.DateTime.Now.ToString() + "\"},\"registration_ids\":[\"" + regIds + "\"]}";
//string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&date.time=" + System.DateTime.Now.ToString() + "®istration_ids=" + regIds + "";
Console.WriteLine(postData);
Byte[] bytes = Encoding.UTF8.GetBytes(postData);
wRequest.ContentLength = bytes.Length;
Stream stream = wRequest.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
WebResponse wResponse = wRequest.GetResponse();
stream = wResponse.GetResponseStream();
StreamReader reader = new StreamReader(stream);
String response = reader.ReadToEnd();
HttpWebResponse httpResponse = (HttpWebResponse)wResponse;
string status = httpResponse.StatusCode.ToString();
reader.Close();
stream.Close();
wResponse.Close();
if (status == "")
{
return response;
}
else
{
return "";
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
Console.WriteLine();
return "";
}
}
private class NotificationMessage
{
public string Title;
public string Message;
public long ItemId;
}
}
}
The postData isn't properly formatted in JSON. If you check it out using an online formatting tool, it looks like this
{
"collapse_key":"standard",
"time_to_live":108,
"delay_while_idle":true,
"dry_run":true,
"data":{
"message":"{"Title":"test",
"Message":"HelloWorld",
"ItemId":220299}",
"time":"22/04/2016 13:04:38"
},
"registration_ids":["aaaaaaaaaaaaaaaaaaaaaaaa"]
}
You can either remove the data.message node and place its properties in data, or use a 3rd-party JSON parser or System.Web.Helpers.Json.Decode (which were suggested in this issue)
Hopefully this helps with the issue.
Happy coding!
I am stuck on implementing the Yahoo Weather private API call. This is my code snippet, whenever I call it using valid clientId & Secret it returns 401 (unauthorized).
var outhWc = new WebClient();
outhWc.Credentials = new NetworkCredential(clientId, clientSecret);
outhWc.Headers.Add(HttpRequestHeader.Accept, "application/json");
var outhresponse = outhWc.DownloadData("https://query.yahooapis.com/v1/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&format=json");
It always throws an exception. I also try to pass username and password in NetworkCredentials and also try to pass clientId and Secret in Header but I cannot find a successful call.
So I've been stuck with the same issue here. Finally I implemented the following code, based on the oAuth c# simple class found at http://oauth.googlecode.com/svn/code/csharp/OAuthBase.cs
public void LoadWeather() {
string URLDes, Params = "";
string Signature, BaseURL, cKey, cSecret = "";
OAuthBase oAuth = new OAuthBase();
BaseURL = "http://weather.yahooapis.com/forecastrss?w=" + textBox1.Text + "&u=f";
cKey = "YOUR API KEY";
cSecret = "YOUR API SECRET";
Signature = oAuth.GenerateSignature(new Uri(BaseURL), cKey, cSecret, "", "", "GET", oAuth.GenerateTimeStamp(), oAuth.GenerateNonce(), out URLDes, out Params);
WebClient wc = new WebClient();
wc.DownloadStringCompleted += HttpsCompleted;
wc.DownloadStringAsync(new Uri(String.Format("{0}?{1}&oauth_signature={2}", URLDes, Params, Signature)));
}
private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e) {
if (e.Error == null) {
XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None);
xdoc.Save("c:\\weather.xml");
richTextBox1.Text = xdoc.FirstNode.ToString();
} else {
richTextBox1.Text = e.Error.Message;
}
}
As you can see, I already have the city ID. This sample downloads the xml string returned by the API. Worked for me, hope it helps!