Post Tweet Using Tweetsharp

(0.04328083992 seconds)
31531 pages : 123456789Next ›Last»

jrgcubano/posttweet.cs( c)

// From https://blog.dantup.com/2016/07/simplest-csharp-code-to-post-a-tweet-using-oauth/

/// <summary>
/// Simple class for sending tweets to Twitter using Single-user OAuth.
/// https://dev.twitter.com/oauth/overview/single-user
/// 
/// Get your access keys by creating an app at apps.twitter.com then visiting the
/// "Keys and Access Tokens" section for your app. They can be found under the
/// "Your Access Token" heading.
/// </summary>
class TwitterApi
{
	const string TwitterApiBaseUrl = "https://api.twitter.com/1.1/";
	readonly string consumerKey, consumerKeySecret, accessToken, accessTokenSecret;
	readonly HMACSHA1 sigHasher;
	readonly DateTime epochUtc = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

	/// <summary>
	/// Creates an object for sending tweets to Twitter using Single-user OAuth.
	/// 
	/// Get your access keys by creating an app at apps.twitter.com then visiting the
	/// "Keys and Access Tokens" section for your app. They can be found under the
	/// "Your Access Token" heading.
	/// </summary>
	public TwitterApi(string consumerKey, string consumerKeySecret, string accessToken, string accessTokenSecret)
	{
		this.consumerKey = consumerKey;
		this.consumerKeySecret = consumerKeySecret;
		this.accessToken = accessToken;
		this.accessTokenSecret = accessTokenSecret;

		sigHasher = new HMACSHA1(new ASCIIEncoding().GetBytes(string.Format("{0}&{1}", consumerKeySecret, accessTokenSecret)));
	}

	/// <summary>
	/// Sends a tweet with the supplied text and returns the response from the Twitter API.
	/// </summary>
	public Task<string> Tweet(string text)
	{
		var data = new Dictionary<string, string> {
			{ "status", text },
			{ "trim_user", "1" }
		};

		return SendRequest("statuses/update.json", data);
	}

	Task<string> SendRequest(string url, Dictionary<string, string> data)
	{
		var fullUrl = TwitterApiBaseUrl + url;

		// Timestamps are in seconds since 1/1/1970.
		var timestamp = (int)((DateTime.UtcNow - epochUtc).TotalSeconds);

		// Add all the OAuth headers we'll need to use when constructing the hash.
		data.Add("oauth_consumer_key", consumerKey);
		data.Add("oauth_signature_method", "HMAC-SHA1");
		data.Add("oauth_timestamp", timestamp.ToString());
		data.Add("oauth_nonce", "a"); // Required, but Twitter doesn't appear to use it, so "a" will do.
		data.Add("oauth_token", accessToken);
		data.Add("oauth_version", "1.0");

		// Generate the OAuth signature and add it to our payload.
		data.Add("oauth_signature", GenerateSignature(fullUrl, data));

		// Build the OAuth HTTP Header from the data.
		string oAuthHeader = GenerateOAuthHeader(data);

		// Build the form data (exclude OAuth stuff that's already in the header).
		var formData = new FormUrlEncodedContent(data.Where(kvp => !kvp.Key.StartsWith("oauth_")));

		return SendRequest(fullUrl, oAuthHeader, formData);
	}

	/// <summary>
	/// Generate an OAuth signature from OAuth header values.
	/// </summary>
	string GenerateSignature(string url, Dictionary<string, string> data)
	{
		var sigString = string.Join(
			"&",
			data
				.Union(data)
				.Select(kvp => string.Format("{0}={1}", Uri.EscapeDataString(kvp.Key), Uri.EscapeDataString(kvp.Value)))
				.OrderBy(s => s)
		);

		var fullSigData = string.Format(
			"{0}&{1}&{2}",
			"POST",
			Uri.EscapeDataString(url),
			Uri.EscapeDataString(sigString.ToString())
		);

		return Convert.ToBase64String(sigHasher.ComputeHash(new ASCIIEncoding().GetBytes(fullSigData.ToString())));
	}

	/// <summary>
	/// Generate the raw OAuth HTML header from the values (including signature).
	/// </summary>
	string GenerateOAuthHeader(Dictionary<string, string> data)
	{
		return "OAuth " + string.Join(
			", ",
			data
				.Where(kvp => kvp.Key.StartsWith("oauth_"))
				.Select(kvp => string.Format("{0}=\"{1}\"", Uri.EscapeDataString(kvp.Key), Uri.EscapeDataString(kvp.Value)))
				.OrderBy(s => s)
		);
	}

	/// <summary>
	/// Send HTTP Request and return the response.
	/// </summary>
	async Task<string> SendRequest(string fullUrl, string oAuthHeader, FormUrlEncodedContent formData)
	{
		using (var http = new HttpClient())
		{
			http.DefaultRequestHeaders.Add("Authorization", oAuthHeader);

			var httpResp = await http.PostAsync(fullUrl, formData);
			var respBody = await httpResp.Content.ReadAsStringAsync();

			return respBody;
		}
	}
}


// Use it 
var twitter = new TwitterApi(ConsumerKey, ConsumerKeySecret, AccessToken, AccessTokenSecret);
var response = await twitter.Tweet("This is my first automated tweet!");
Console.WriteLine(response);

Post tweet using C#
Loading...

doppiomacchiatto/Tweet Stream using pyspark.md( python)

import pyspark_cassandra
from pyspark.streaming import StreamingContext
from pyspark import SparkConf, SparkContext
from pyspark_cassandra import streaming

keyspace, table = "mykeyspace", "tweets"

conf = SparkConf() \
	    .setAppName("PySpark Cassandra Stream") \
	    .setMaster("spark://SANM-MBP01L.local:7077") \
	    .set("spark.cassandra.connection.host", "localhost") \
        .set("spark.eventLog.enabled", "true") \
        .set("spark.jars.packages", 'TargetHolding/pyspark-cassandra:0.3.5')

sc = pyspark_cassandra.CassandraSparkContext(conf=conf)

ssc = StreamingContext(sc, 2)

log4j = sc._jvm.org.apache.log4j
log4j.LogManager.getRootLogger().setLevel(log4j.Level.ERROR)

def split_ip(line):
    id_str, created_at = line.split()
    return (created_at, 3,)

rdds = ssc \
    .socketTextStream("10.0.0.235", 9999) \
    .map(split_ip)

rdds.pprint()

rdds.saveToCassandra(keyspace, table)

ssc.start()
ssc.awaitTerminationOrTimeout(100)
ssc.stop()

Spark Cassandra Live Tweet Example 1

akirattii/tweet-bot-using-nightmare.js( javascript)

// TODO: Change your username/password:
const TW_USER = "<YOUR_USERNAME>";
const TW_PASS = "<YOUR_PASSWORD>";

var Nightmare = require('nightmare');
var nightmare = Nightmare({ show: true });

nightmare
  .goto('https://twitter.com/login/')
  .insert('.js-username-field.email-input.js-initial-focus[name="session[username_or_email]"]', TW_USER)
  .insert(".js-password-field[name='session[password]']", TW_PASS)
  .click('#page-container > div > div.signin-wrapper > form > div.clearfix > button')
  .wait(2000)
  .goto("https://twitter.com/settings/account")
  .evaluate(function() {
    return document.querySelector('#username_fieldset > div > p:nth-child(3)').innerText;
  })
  // open the tweet panel
  .click("#global-new-tweet-button > span.Icon.Icon--tweet.Icon--large") 
  // tweets "hello"
  .type('#tweet-box-global', 'hello')
  // click to send
  .click("#global-tweet-dialog-dialog > div.modal-content > div.modal-tweet-form-container > form > div.TweetBoxToolbar > div.TweetBoxToolbar-tweetButton.tweet-button > button > span.button-text.tweeting-text")
  .end()
  .then(function(result) {
    console.log(result);
  })
  .catch(function(error) {
    console.error('Search failed:', error);
  });


Tweetbot example using Nightmare

tobynet/[Practice] Tweet Box Using jQuery.markdown( html)

[Practice] Tweet Box Using jQuery
---------------------------------
http://reactfordesigners.com/labs/reactjs-introduction-for-people-who-know-just-enough-jquery-to-get-by/

A [Pen](http://codepen.io/tobynet/pen/ojPPpg) by [TOBY](http://codepen.io/tobynet) on [CodePen](http://codepen.io/).

[License](http://codepen.io/tobynet/pen/ojPPpg/license).

[Practice] Tweet Box Using jQuery

tobynet/[Practice] Tweet Box Using React.js.markdown( html)

[Practice] Tweet Box Using React.js
-----------------------------------
http://reactfordesigners.com/labs/reactjs-introduction-for-people-who-know-just-enough-jquery-to-get-by/

A [Pen](http://codepen.io/tobynet/pen/ojPJRx) by [TOBY](http://codepen.io/tobynet) on [CodePen](http://codepen.io/).

[License](http://codepen.io/tobynet/pen/ojPJRx/license).

[Practice] Tweet Box Using React.js

ivconejera/Post_tweet.cs( c)

public void UpdateStatus(string message)
{
	// Application tokens
	const string CONSUMER_KEY = "YOUR_CONSUMER_KEY";
	const string CONSUMER_SECRET = "YOUR_CONSUMER_SECRET";
	// Access tokens
	const string ACCESS_TOKEN = "YOUR_ACCESS_TOKEN";
	const string ACCESS_TOKEN_SECRET = "YOUR_ACCESS_TOKEN_SECRET";
	
	// Common parameters
	const string VERSION = "1.0";
	const string SIGNATURE_METHOD = "HMAC-SHA1";

	// Parameters specific to this request
	var nonce = new Random().Next(0x0000000, 0x7fffffff).ToString("X8");
	var timestamp = ((int) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString();

	// Prepare the text to sign
	var dataToSign = new StringBuilder();
	dataToSign
		.Append("POST")
		.Append("&")
		.Append("http://api.twitter.com/1/statuses/update.xml".EncodeRFC3986())
		.Append("&");

	// Values to sign: oauth parameters AND request parameters
	var signatureParts = new Dictionary<string, string>
	{
		{"status", message.EncodeRFC3986()},
		{"oauth_version", VERSION},
		{"oauth_consumer_key", CONSUMER_KEY},
		{"oauth_nonce", nonce},
		{"oauth_signature_method", SIGNATURE_METHOD},
		{"oauth_timestamp", timestamp},
		{"oauth_token", ACCESS_TOKEN}
	};

	dataToSign.Append(
		signatureParts
			.OrderBy(x => x.Key)
			.Select(x => "{0}={1}".FormatWith(x.Key, x.Value))
			.Join("&")
			.EncodeRFC3986());

	// Calculate the signature key required to sign the request
	var signatureKey = "{0}&{1}".FormatWith(CONSUMER_SECRET.EncodeRFC3986(), ACCESS_TOKEN_SECRET.EncodeRFC3986());
	var sha1 = new HMACSHA1(Encoding.ASCII.GetBytes(signatureKey));

	var signatureBytes = sha1.ComputeHash(Encoding.ASCII.GetBytes(dataToSign.ToString()));
	var signature = Convert.ToBase64String(signatureBytes);

	// Create and setup the actual request
	var request = (HttpWebRequest) WebRequest.Create("http://api.twitter.com/1/statuses/update.xml");
	request.Method = "POST";
	request.ContentType = "application/x-www-form-urlencoded";

	// Set authorization header
	request.Headers.Add(
		"Authorization",
		new StringBuilder("OAuth ")
			.AppendFormat("{0}=\"{1}\"", "oauth_nonce".EncodeRFC3986(), nonce.EncodeRFC3986()).Append(",")
			.AppendFormat("{0}=\"{1}\"", "oauth_signature_method".EncodeRFC3986(), SIGNATURE_METHOD.EncodeRFC3986()).Append(",")
			.AppendFormat("{0}=\"{1}\"", "oauth_timestamp".EncodeRFC3986(), timestamp.EncodeRFC3986()).Append(",")
			.AppendFormat("{0}=\"{1}\"", "oauth_consumer_key".EncodeRFC3986(), CONSUMER_KEY.EncodeRFC3986()).Append(",")
			.AppendFormat("{0}=\"{1}\"", "oauth_token".EncodeRFC3986(), ACCESS_TOKEN.EncodeRFC3986()).Append(",")
			.AppendFormat("{0}=\"{1}\"", "oauth_signature".EncodeRFC3986(), signature.EncodeRFC3986()).Append(",")
			.AppendFormat("{0}=\"{1}\"", "oauth_version".EncodeRFC3986(), VERSION.EncodeRFC3986())
			.ToString());

	// Add request body with request parameters
	var requestBody = Encoding.ASCII.GetBytes("status={0}".FormatWith(message.EncodeRFC3986()));
	using (var stream = request.GetRequestStream())
		stream.Write(requestBody, 0, requestBody.Length);

	// ... and here we go!
	request.GetResponse();

	// We could analyze the response, but since we'll get an exception if 
        // something fails, we don't need to mess with response content
}
	
public static string Join<T>(this IEnumerable<T> items, string separator)
{
	return string.Join(separator, items.ToArray());
}

public static string FormatWith(this string format, params object[] args)
{
	return string.Format(format, args);
}

// From Twitterizer http://www.twitterizer.net/
public static string EncodeRFC3986(this string value)
{
	if (string.IsNullOrEmpty(value))
		return string.Empty;

	var encoded = Uri.EscapeDataString(value);

	return Regex
		.Replace(encoded, "(%[0-9a-f][0-9a-f])", c => c.Value.ToUpper())
		.Replace("(", "%28")
		.Replace(")", "%29")
		.Replace("$", "%24")
		.Replace("!", "%21")
		.Replace("*", "%2A")
		.Replace("'", "%27")
		.Replace("%7E", "~");
}

Post tweet

alexkingorg/wp-post-content-tweet.php( php)

<?php

function aktt_replace_tweet_content($posts) {
	foreach ($posts as $post) {
		if ($post->post_type == AKTT::$post_type && !empty($post->tweet)) {
			$post->post_content = esc_url(AKTT::status_url($post->tweet->username(), $post->tweet->id()));
		}
	}
}
add_action('the_posts', 'aktt_replace_tweet_content', 11);


Replace post content with tweet URL using Twitter Tools data.

sugtao4423/tweet.php( php)

<?php

function tweet($status = ''){
    $url = 'https://api.twitter.com/1.1/statuses/update.json';

    $consumer_key = '*****';
    $consumer_secret = '*****';
    $token = '*****';
    $token_secret = '*****';

    $header = array(
        'oauth_consumer_key'     => $consumer_key,
        'oauth_signature_method' => 'HMAC-SHA1',
        'oauth_timestamp'        => time(),
        'oauth_version'          => '1.0a',
        'oauth_nonce'            => bin2hex(openssl_random_pseudo_bytes(16)),
        'oauth_token'            => $token,
    );
    $content = array(
        'status' => $status
    );

    $base = $header + $content;
    ksort($base);
    $base = http_build_query($base, '', '&', PHP_QUERY_RFC3986);
    $base = array('POST', $url, $base);
    $base = array_map('rawurlencode', $base);
    $base = implode('&', $base);

    $key = array_map('rawurlencode', array($consumer_secret, $token_secret));
    $key = implode('&', $key);

    $header['oauth_signature'] = base64_encode(hash_hmac('sha1', $base, $key, true));

    foreach($header as $name => $value){
        $items[] = urlencode($name) . '="' . urlencode($value) . '"';
    }
    $header = 'Authorization: OAuth ' . implode(', ', $items);

    return @file_get_contents($url, false, stream_context_create(array(
        'http' => array(
            'method' => 'POST',
            'header' => $header,
            'content' => http_build_query($content)
    ))));
}


post tweet without library

EricDing/Form POST using $http.markdown( html)

Form POST using $http
---------------------
Using Content type application/x-www-form-urlencoded and encoding the parameters that are passed in the body.

A [Pen](https://codepen.io/EricDing/pen/zBqvqE) by [Eric](http://codepen.io/EricDing) on [CodePen](http://codepen.io/).

[License](https://codepen.io/EricDing/pen/zBqvqE/license).

Form POST using $http

proclaim/post-json-using-fetch.js( javascript)

const headers = new Headers(),
      payload = { name: 'yoshie', age: 24 }
      url = 'http://172.16.2.64/api/v1';

headers.append('Content-Type', 'application/json');

const request = new Request(url, {
   method: 'POST', 
   mode: 'no-cors',
   body: JSON.stringify(payload),
   headers: headers
});

fetch(request)
  .then(response => response.json())
  .then(result => {
    console.log(result);
  })
  .catch(e => {
    console.log(e);
  })

correct way of posting json using fetch