public void Send(string Message, TwitterService ts) { string randomPicture = Helpers.GetRandomPicture(); using (var stream = new CustomFileStream(randomPicture, FileMode.Open, 5000, 5000)) { var tweet = new SendTweetWithMediaOptions { Status = Message, Images = new Dictionary <string, Stream> { { "Gundel", stream } } }; try { ts.SendTweetWithMedia(tweet); } catch (FileNotFoundException) { } } Helpers.Log(Message, _status); }
public void Tweet(string message, string hashTag, string picture) { if (CalcurateTweetLength(message, hashTag, picture) > 140) { throw new ArgumentException("文字数が多すぎます。"); } if (twitterService_ == null) { twitterService_ = new TwitterService(consumerKey_, consumerSecret_); twitterService_.AuthenticateWith(accessToken_, accessTokenSecret_); } var str = CreateTweetText(message, hashTag); if (picture != null) { SendTweetWithMediaOptions opt = new SendTweetWithMediaOptions(); using (var fs = new FileStream(picture, FileMode.Open, FileAccess.Read, FileShare.Read)) { opt.Images = new Dictionary <string, Stream> { { "image", fs } }; opt.Status = str; twitterService_.SendTweetWithMedia(opt); } } else { var opt = new SendTweetOptions(); opt.Status = str; twitterService_.SendTweet(opt); } }
static void postTweet(string tweetBody, string imagePath) { try { Stream image = new FileStream("output.png", FileMode.Open); // This wrapper is weird so we've got to put our image in a Dictionary first // (but allegedly the key doesn't do anything?) // I'm just going to put the filename in there, so it looks like I know what I'm doing Dictionary <string, Stream> imageHolder = new Dictionary <string, Stream>(); imageHolder.Add("output.png", image); // TwitterService doesn't implement IDisposable // Uh, I don't *think* that's a problem?? TwitterService service = new TwitterService(Auth.AUTH_CONSUMER_KEY, Auth.AUTH_CONSUMER_SECRET); service.AuthenticateWith(Auth.AUTH_ACCESS_TOKEN, Auth.AUTH_ACCESS_TOKEN_SECRET); // siri_send_tweet() SendTweetWithMediaOptions tweetOptions = new SendTweetWithMediaOptions(); tweetOptions.Status = tweetBody; tweetOptions.Images = imageHolder; service.SendTweetWithMedia(tweetOptions); log("TWEETED: " + tweetBody); } catch (Exception e) // What kind of exception does TweetSharp throw and why can I not figure this out? { Console.WriteLine(e.Message); log(e.Message); // I just don't know, man } }
public void TweetWithImage() { try { //ステータスリスト List <TwitterService> ResponseList = new List <TwitterService>(); //各アカウントでつぶやく foreach (Core.ApplicationSetting.AccountClass account in AccountList) { //ファイルのストリームを取得 System.IO.Stream stream = Song.getAlbumArtworkFileStream(); TwitterService service = new TwitterService(Core.Twitter.CONSUMERKEY, Core.Twitter.CONSUMERSECRET); service.AuthenticateWith(account.Token, account.TokenSecret); SendTweetWithMediaOptions opt = new SendTweetWithMediaOptions(); opt.Status = Core.Replace.ReplaceText(TweetText, Song); // ツイートする内容 //テキストを自動的に削るやつ if (AutoDeleteText == true && opt.Status.Length > 117) { opt.Status = opt.Status.Remove(114);//...の三文字分含めて削除 opt.Status += "..."; } //opt.Status = HttpUtility.UrlEncode(opt.Status); opt.Images = new Dictionary <string, System.IO.Stream> { { "image", stream } }; //Luaの関数を走らせる try { bool luaRet = (bool)luaFunc.Call(Song, opt, isCustomTweet)[0]; if (luaRet == true) { service.SendTweetWithMedia(opt); ResponseList.Add(service); } } catch (Exception ex2) { //Luaが失敗しても死なないようにする Trace.WriteLine("Lua error."); Trace.WriteLine(ex2.ToString()); service.SendTweetWithMedia(opt); ResponseList.Add(service); } stream.Close(); stream.Dispose(); } //完了イベントを投げる onProcessFinished(ResponseList); } catch (Exception ex) { Trace.WriteLine("[TwitterPost ERROR]" + ex.ToString()); } }
/// <summary> /// Post /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void bntPost_Click(object sender, EventArgs args) { pgbPost.Value = 0; pgbPost.Maximum = ds_media.Tables[0].Rows.Count; for (int idx = 0; idx < ds_media.Tables[0].Rows.Count; idx++) { String mediaPublishId = ds_media.Tables[0].Rows[idx]["发布编号"].ToString(); setMediaPublishStatus(mediaPublishId, "发行中"); string content = ds_media.Tables[0].Rows[idx]["名称"].ToString() + ds_media.Tables[0].Rows[idx]["发行期号"].ToString() + "[" + ds_media.Tables[0].Rows[idx]["发行日期"].ToString() + "]\r\n" + ds_media.Tables[0].Rows[idx]["文本内容"].ToString(); string picpath = ds_media.Tables[0].Rows[idx]["本地图片"].ToString(); try { SendTweetWithMediaOptions sendOptions = new SendTweetWithMediaOptions(); sendOptions.Images = new Dictionary <string, Stream>(); sendOptions.Images.Add(Path.GetFileName(picpath), new FileStream(picpath, FileMode.Open, FileAccess.Read)); if (content.Length > 70) { content = content.Substring(0, 70); } sendOptions.Status = content; if (service.SendTweetWithMedia(sendOptions) != null) { setMediaPublishStatus(mediaPublishId, "发行完"); } else { setMediaPublishStatus(mediaPublishId, "未发行"); } } catch (Exception ex) { setMediaPublishStatus(mediaPublishId, "未发行"); NCLogger.GetInstance().WriteExceptionLog(ex); } } }
static public TwitterItem writeNewTweet(AccountTwitter account, string text, string upload_image_path = null) { try { TwitterStatus status = null; if (string.IsNullOrEmpty(upload_image_path)) { SendTweetOptions options = new TweetSharp.SendTweetOptions(); options.Status = text; status = account.twitterService.SendTweet(options); } else { SendTweetWithMediaOptions media_options = new SendTweetWithMediaOptions(); media_options.Status = text; FileStream file_stream = System.IO.File.OpenRead(upload_image_path); Dictionary <string, Stream> image_dictionary = new Dictionary <string, Stream>(); image_dictionary.Add(upload_image_path, file_stream); media_options.Images = image_dictionary; status = account.twitterService.SendTweetWithMedia(media_options); } if (status != null) { return(API.TweetSharpConverter.getItemFromStatus(status, account)); } else { System.Windows.MessageBox.Show("Failed", "Sending of tweet failed"); return(null); } } catch (Exception exp) { System.Windows.MessageBox.Show(exp.Message, "Sending of tweet failed"); return(null); } }
/// <summary> /// 媒体连接测试 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnTest_Click(object sender, EventArgs ex) { if (dataGridView1.SelectedRows.Count > 0) { string mediaType = cmbMediaType.Text; string mediaUrl = txtMediaURL.Text; string appKey = txtAppKey.Text; string appPassword = txtAppPassword.Text; string user = txtUserName.Text; string password = txtPassword.Text; string content = txtOther.Text; string pic = txtTestImage.Text; if (File.Exists(pic)) { switch (mediaType) { case "TENCENT": FormQWeiboLogin LoginDlg = new FormQWeiboLogin(appKey, appPassword, user, password); LoginDlg.ShowDialog(); if (LoginDlg.Comfirm) { OauthKey oauthKey = new OauthKey(); oauthKey.customKey = LoginDlg.AppKey; oauthKey.customSecret = LoginDlg.AppSecret; oauthKey.tokenKey = LoginDlg.AccessKey; oauthKey.tokenSecret = LoginDlg.AccessSecret; ///发送带图片微博 t twit = new t(oauthKey, "json"); UTF8Encoding utf8 = new UTF8Encoding(); string ret = twit.add_pic(utf8.GetString(utf8.GetBytes(content)), utf8.GetString(utf8.GetBytes("127.0.0.1")), utf8.GetString(utf8.GetBytes("")), utf8.GetString(utf8.GetBytes("")), utf8.GetString(utf8.GetBytes(pic)) ); string msg = NCMessage.GetInstance(db.Language).GetMessageById("CM0057I", db.Language); MessageBox.Show(msg); } break; case "WORDPRESS": IMetaWeblog metaWeblog = (IMetaWeblog)XmlRpcProxyGen.Create(typeof(IMetaWeblog)); XmlRpcClientProtocol clientProtocol = (XmlRpcClientProtocol)metaWeblog; clientProtocol.Url = mediaUrl; string picURL = null; string filename = pic; if (File.Exists(filename)) { FileData fileData = default(FileData); fileData.name = Path.GetFileName(filename); fileData.type = Path.GetExtension(filename); try { FileInfo fi = new FileInfo(filename); using (BinaryReader br = new BinaryReader(new FileStream(filename, FileMode.Open, FileAccess.Read))) { fileData.bits = br.ReadBytes((int)fi.Length); } UrlData urlData = metaWeblog.newMediaObject("6", user, password, fileData); picURL = urlData.url; } catch (Exception exc) { NCLogger.GetInstance().WriteExceptionLog(exc); } } Post newBlogPost = default(Post); newBlogPost.title = content; newBlogPost.description = ""; newBlogPost.categories = new string[1]; newBlogPost.categories[0] = cmbCategry.Text; newBlogPost.dateCreated = System.DateTime.Now; if (picURL != null) { newBlogPost.description += "<br><img src='" + picURL + "'/>"; } try { string result = metaWeblog.newPost("6", user, password, newBlogPost, true); } catch (Exception ex2) { NCLogger.GetInstance().WriteExceptionLog(ex2); } break; case "FACEBOOK": var fbLoginDlg = new FormFacebookLogin(appKey, user, password); fbLoginDlg.ShowDialog(); if (fbLoginDlg.FacebookOAuthResult != null && fbLoginDlg.FacebookOAuthResult.IsSuccess) { string _accessToken = fbLoginDlg.FacebookOAuthResult.AccessToken; var fb = new FacebookClient(_accessToken); // make sure to add event handler for PostCompleted. fb.PostCompleted += (o, e) => { // incase you support cancellation, make sure to check // e.Cancelled property first even before checking (e.Error!=null). if (e.Cancelled) { // for this example, we can ignore as we don't allow this // example to be cancelled. // you can check e.Error for reasons behind the cancellation. var cancellationError = e.Error; } else if (e.Error != null) { // error occurred this.BeginInvoke(new MethodInvoker( () => { MessageBox.Show(e.Error.Message); })); } else { // the request was completed successfully // make sure to be on the right thread when working with ui. this.BeginInvoke(new MethodInvoker( () => { //MessageBox.Show("Picture uploaded successfully"); Application.DoEvents(); })); } }; dynamic parameters = new ExpandoObject(); parameters.message = content; parameters.source = new FacebookMediaObject { ContentType = "image/jpeg", FileName = Path.GetFileName(pic) }.SetValue(File.ReadAllBytes(pic)); fb.PostAsync("me/photos", parameters); } break; case "TWITTER": TwitterService service = new TwitterService(appKey, appPassword); FormTwitterLogin form = new FormTwitterLogin(db, service); if (form.ShowDialog() == DialogResult.OK) { SendTweetWithMediaOptions sendOptions = new SendTweetWithMediaOptions(); sendOptions.Images = new Dictionary <string, Stream>(); sendOptions.Images.Add(Path.GetFileName(pic), new FileStream(pic, FileMode.Open, FileAccess.Read)); if (content.Length > 70) { content = content.Substring(0, 70); } sendOptions.Status = content; if (service.SendTweetWithMedia(sendOptions) != null) { string msg = NCMessage.GetInstance(db.Language).GetMessageById("CM0057I", db.Language); MessageBox.Show(msg); } } break; case "LINKEDIN": OAuth1 _OAuthLinkedin = new OAuth1(db); _OAuthLinkedin.Settings_Provider = "Linkedin"; _OAuthLinkedin.Settings_ConsumerKey = appKey; _OAuthLinkedin.Settings_ConsumerSecret = appPassword; _OAuthLinkedin.Settings_AccessToken_page = "https://api.linkedin.com/uas/oauth/accessToken"; _OAuthLinkedin.Settings_Authorize_page = "https://api.linkedin.com/uas/oauth/authorize"; _OAuthLinkedin.Settings_RequestToken_page = "https://api.linkedin.com/uas/oauth/requestToken"; _OAuthLinkedin.Settings_Redirect_URL = "http://www.chojo.co.jp/"; _OAuthLinkedin.Settings_User_agent = "CJW"; _OAuthLinkedin.Settings_OAuth_Realm_page = "https://api.linkedin.com/"; _OAuthLinkedin.Settings_GetProfile_API_page = "https://api.linkedin.com/v1/people/~/"; _OAuthLinkedin.Settings_StatusUpdate_API_page = "https://api.linkedin.com/v1/people/~/current-status"; _OAuthLinkedin.getRequestToken(); _OAuthLinkedin.authorizeToken(); String accessToken = _OAuthLinkedin.getAccessToken(); try { string ret = _OAuthLinkedin.APIWebRequest("POST", _OAuthLinkedin.Settings_StatusUpdate_API_page, pic); string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; xml += "<current-status>" + txtOther.Text + "<img src =" + ret + "/>" + "</current-status>"; _OAuthLinkedin.APIWebRequest("PUT", _OAuthLinkedin.Settings_StatusUpdate_API_page, xml); } catch (Exception exp) { MessageBox.Show(exp.Message); } break; case "MSN": case "GOOGLE": case "YAHOO": PROVIDER_TYPE provider_type = (PROVIDER_TYPE)Enum.Parse(typeof(PROVIDER_TYPE), mediaType); setConfigure(user, password, mediaType); FormAuthSocialLogin loginForm = new FormAuthSocialLogin(db, provider_type, socialAuthManager); if (loginForm.ShowDialog() == DialogResult.OK) { string msgs = HttpUtility.UrlEncode(content); string endpoint = mediaUrl + msgs; string body = String.Empty; //byte[] reqbytes = new ASCIIEncoding().GetBytes(body); byte[] reqbytes = File.ReadAllBytes(pic); Dictionary <string, string> headers = new Dictionary <string, string>(); //headers.Add("contentType", "application/x-www-form-urlencoded"); headers.Add("contentType", "image/jpeg"); headers.Add("FileName", Path.GetFileName(pic)); var response = socialAuthManager.ExecuteFeed( endpoint, TRANSPORT_METHOD.POST, provider_type, reqbytes, headers ); } break; } } else { string msg = NCMessage.GetInstance(db.Language).GetMessageById("CM0058I", db.Language); MessageBox.Show(msg); } } else { string msg = NCMessage.GetInstance(db.Language).GetMessageById("CM0050I", db.Language); MessageBox.Show(msg); } }
/// <summary> /// Sets an user status. /// </summary> /// <param name="status">Status entity.</param> public async Task SetStatusAsync(TwitterStatus status) { // Pass your credentials to the service string consumerKey = _settings.TwitterConsumerKey; string consumerSecret = _settings.TwitterConsumerSecret; // Authorize var service = new TwitterService(consumerKey, consumerSecret); service.AuthenticateWith(status.Token, status.TokenSecret); // Send message TweetSharp.TwitterStatus result; if (string.IsNullOrEmpty(status.ScreenshotUrl)) { var tweet = new SendTweetOptions { Status = status.Message }; result = service.SendTweet(tweet); } else { using (var httpClient = new HttpClient()) { HttpResponseMessage response = await httpClient.GetAsync(status.ScreenshotUrl); if (!response.IsSuccessStatusCode) { throw new BadRequestException(response.ReasonPhrase); } Stream stream = await response.Content.ReadAsStreamAsync(); var tweet = new SendTweetWithMediaOptions { Status = status.Message, Images = new Dictionary <string, Stream> { { "media", stream } } }; result = service.SendTweetWithMedia(tweet); } } // Check result status if (result != null) { return; } // Check response status code switch (service.Response.StatusCode) { case HttpStatusCode.Unauthorized: case HttpStatusCode.BadRequest: // Invalid credentials or request data throw new BadRequestException(service.Response.Response); case HttpStatusCode.Forbidden: throw new ForbiddenException(service.Response.Response); case (HttpStatusCode)429: throw new TooManyRequestsException(service.Response.Response); } // Twitter internal errors if ((int)service.Response.StatusCode >= 500) { throw new BadGatewayException(service.Response.Response); } string message = string.Format("Unable to send tweet. Status code {0}: {1}", service.Response.StatusCode, service.Response); throw new InternalServerErrorException(message); }