コード例 #1
0
ファイル: TwittsProvider.cs プロジェクト: Jacobeom/git-first
        public IList<NakedTwitt> RetrieveTwitts(int count)
        {
            List<NakedTwitt> result = new List<NakedTwitt>();

            try
            {
                OAuthTokens tokens = new OAuthTokens()
                                         {
                                             AccessToken = AccessToken,
                                             AccessTokenSecret = AccessTokenSecret,
                                             ConsumerKey = ConsumerKey,
                                             ConsumerSecret = ConsumerSecret
                                         };

                TimelineOptions timelineOptions = new TimelineOptions()
                                                      {
                                                          Count = count,
                                                          IncludeRetweets = false
                                                      };

                TwitterResponse<TwitterStatusCollection> homeTimeline = TwitterTimeline.HomeTimeline(tokens,
                                                                                                     timelineOptions);
                result =
                    homeTimeline.ResponseObject.Select(
                        x => new NakedTwitt() {StringId = x.StringId, Text = x.Text, CreatedDate = x.CreatedDate})
                                .ToList();

                return result;
            }
            catch (Exception ex)
            {
                log.Error("Error retrieving twitts from the internet", ex);
                return result;
            }
        }
コード例 #2
0
        /// <summary>
        /// Gets tweets posted by specified user
        /// </summary>
        /// <param name="messageCount">Message count</param>
        /// <returns>Message list</returns>
        public List <Message> GetUserTweets(decimal?userID, string screenName, int messageCount)
        {
            try
            {
                Twitterizer.OAuthTokens tokens = GetOAuthTokens();

                Twitterizer.UserTimelineOptions options = new Twitterizer.UserTimelineOptions();
                options.ScreenName = screenName;
                if (userID.HasValue)
                {
                    options.UserId = userID.Value;
                }
                options.IncludeRetweets = true;
                options.Count           = messageCount;

                TwitterResponse <TwitterStatusCollection> statusResponse = TwitterTimeline.UserTimeline(tokens, options);

                if (statusResponse.Result == RequestResult.Success)
                {
                    return(MapMessage(statusResponse.ResponseObject));
                }

                else
                {
                    throw CreateException(statusResponse.Result, statusResponse.ErrorMessage);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw;
            }
        }
コード例 #3
0
        public TwitterSearchStream(TwitterProtocolManager protocolManager,
                                   GroupChatModel chat, string keyword,
                                   OAuthTokens tokens, WebProxy proxy)
        {
            if (protocolManager == null) {
                throw new ArgumentNullException("protocolManager");
            }
            if (chat == null) {
                throw new ArgumentNullException("chat");
            }
            if (keyword == null) {
                throw new ArgumentNullException("keyword");
            }
            if (tokens == null) {
                throw new ArgumentNullException("tokens");
            }

            ProtocolManager = protocolManager;
            Session = protocolManager.Session;
            Chat = chat;

            var options = new StreamOptions();
            options.Track.Add(keyword);

            Stream = new TwitterStream(tokens, null, options);
            Stream.Proxy = proxy;
            Stream.StartPublicStream(OnStreamStopped, OnStatusCreated, OnStatusDeleted, OnEvent);

            MessageRateLimiter = new RateLimiter(5, TimeSpan.FromSeconds(5));
        }
コード例 #4
0
        /// <summary>
        /// Gets the rate limiting status status for the authenticated user.
        /// </summary>
        /// <param name="tokens">The OAuth tokens.</param>
        /// <param name="options">The options.</param>
        /// <returns>
        /// A <see cref="TwitterRateLimitStatus"/> instance.
        /// </returns>
        public static TwitterResponse<TwitterRateLimitStatus> GetStatus(OAuthTokens tokens, OptionalProperties options)
        {
            Commands.RateLimitStatusCommand command = new Twitterizer.Commands.RateLimitStatusCommand(tokens, options);
            TwitterResponse<TwitterRateLimitStatus> result = Core.CommandPerformer.PerformAction(command);

            return result;
        }
コード例 #5
0
ファイル: TwitterPoster.cs プロジェクト: phillco/HellForge
        /// <summary>
        /// Tweets the given message and image; returns the result.
        /// </summary>
        /// <param name="message"></param>
        public static bool Tweet( string message, byte[] resource )
        {
            // Check if we need to authenticate first
            if ( string.IsNullOrEmpty( Configuration.CurrentSettings.TwitterAccessToken ) || string.IsNullOrEmpty( Configuration.CurrentSettings.TwitterAccessSecret ) )
                AcquireAuthentication( );

            // Build tokens...
            OAuthTokens tokens = new OAuthTokens
            {
                 ConsumerKey = ConsumerKey,
                 ConsumerSecret = ConsumerSecret,
                 AccessToken = Configuration.CurrentSettings.TwitterAccessToken,
                 AccessTokenSecret = Configuration.CurrentSettings.TwitterAccessSecret
             };

            TwitterResponse<TwitterStatus> response = TwitterStatus.UpdateWithMedia( tokens, message, resource );
            if ( response.Result == RequestResult.Success )            
                log.Info( "Tweeted: " + message );
            else
            {
                if ( response.Result == RequestResult.Unauthorized )
                    AcquireAuthentication( );

                log.Error( "Error during tweet: " + response.Result + " / " + response.ErrorMessage );
                return false;
            }

            return true;
        }
コード例 #6
0
        /// <summary>
        /// Attempts to verify the supplied credentials.
        /// </summary>
        /// <param name="tokens">The tokens.</param>  
        /// <param name="timeout">The timeout.</param>
        /// <param name="function">The callback or anonymous funtion.</param>
        /// <returns>
        /// The user, as a <see cref="TwitterUser"/>
        /// </returns>       
        public static IAsyncResult VerifyCredentials(OAuthTokens tokens, TimeSpan timeout, Action<TwitterAsyncResponse<TwitterUser>> function)
        {
#if !SILVERLIGHT
            Func<OAuthTokens, TwitterResponse<TwitterUser>> methodToCall = TwitterAccount.VerifyCredentials;

            return methodToCall.BeginInvoke(
                tokens,
                result => 
                {
                    result.AsyncWaitHandle.WaitOne(timeout);
                    try
                    {
                        function(methodToCall.EndInvoke(result).ToAsyncResponse());
                    }
                    catch (Exception ex)
                    {
                        function(new TwitterAsyncResponse<TwitterUser>() { Result = RequestResult.Unknown, ExceptionThrown = ex });
                    }
                },
                null);
#else            
            ThreadPool.QueueUserWorkItem((x) =>
                {
                    function(TwitterAccount.VerifyCredentials(tokens).ToAsyncResponse<TwitterUser>());  
                });
            return null;
#endif
        }
コード例 #7
0
ファイル: frmTeste.cs プロジェクト: AmadeuJunior/LPOO
        public frmPrincipal(Twitterizer.OAuthTokens oauth_tokens)
        {
            //Construtor que recebe o Token do Twitterizer

            TOKEN = oauth_tokens;
            InitializeComponent();
        }
コード例 #8
0
ファイル: Program.cs プロジェクト: kavallo/twitter.GetFriends
        private static IEnumerable<TwitterUser> GetMutualFriends(OAuthTokens tokens)
        {
            var friends = TwitterFriendship.FriendsIds(tokens);
            var followers = TwitterFriendship.FollowersIds(tokens);

            var userIds = (from
                               friendId in friends.ResponseObject
                           join
                               followerId in followers.ResponseObject
                               on friendId equals followerId
                           select friendId).ToArray();

            var lookupOptions = new LookupUsersOptions();
            var users = new List<TwitterUser>();
            for (int i = 0; i < userIds.Length; i ++)
            {
                lookupOptions.UserIds.Add(userIds[i]);
                if (lookupOptions.UserIds.Count() >= 100 || i + 1 == userIds.Length)
                {
                    users.AddRange(TwitterUser.Lookup(tokens, lookupOptions).ResponseObject);
                    lookupOptions.UserIds.Clear();
                }
            }
            return users;
        }
コード例 #9
0
        /// <summary>
        /// Gets current user (defined by access token) home timeline
        /// </summary>
        /// <param name="messageCount">Message count</param>
        /// <returns>Message list</returns>
        public List <Message> GetUserHomeTimeLine(int messageCount)
        {
            try
            {
                Twitterizer.OAuthTokens tokens = GetOAuthTokens();

                Twitterizer.UserTimelineOptions options = new Twitterizer.UserTimelineOptions();
                options.Count           = messageCount;
                options.IncludeRetweets = true;

                TwitterResponse <TwitterStatusCollection> statusResponse = TwitterTimeline.HomeTimeline(tokens, options);

                if (statusResponse.Result == RequestResult.Success)
                {
                    return(MapMessage(statusResponse.ResponseObject));
                }

                else
                {
                    throw CreateException(statusResponse.Result, statusResponse.ErrorMessage);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw;
            }
        }
コード例 #10
0
ファイル: TestController.cs プロジェクト: Otegaman/lehavi-sap
        public ActionResult Test2()
        {
            OAuthTokens tokens = new OAuthTokens { ConsumerKey = ConfigurationManager.AppSettings["TwitterToken"], ConsumerSecret = ConfigurationManager.AppSettings["TwitterTokenSecret"] };

            var accounts = Accounts.Get().Select();
            foreach (var a in accounts)
            {
                if (a.Type == AccountType.Twitter)
                {
                    tokens.AccessToken = a.TwKey;
                    tokens.AccessTokenSecret = a.TwSecret;
                    TwitterResponse<TwitterStatus> tweetResponse = TwitterStatus.Update(tokens, "Hello, #Twitterizer");
                    if (tweetResponse.Result == RequestResult.Success)
                    {
                        // Tweet posted successfully!
                    }
                    else
                    {
                        // Something bad happened
                    }
                }
            }

            return null;
        }
コード例 #11
0
        public static void Tweet(string message)
        {
            throw new NotSupportedException("Remove this when you're ready to Tweet!");
            try
            {
                if (ConfigManager.CurrentUserSpecific.IsValidated)
                    return;
                if (ConfigManager.CurrentUserSpecific.IsEnabled == false)
                    return;
                var currConfig = ConfigManager.CurrentUserSpecific;
                OAuthTokens tokens = new OAuthTokens
                                         {
                                             ConsumerKey = ConsumerKey,
                                             ConsumerSecret = ConsumerSecret,
                                             AccessToken = currConfig.AccessToken,
                                             AccessTokenSecret = currConfig.AccessSecret
                                         };

                TwitterResponse<TwitterStatus> tweetResponse = TwitterStatus.Update(tokens, message);
                if (tweetResponse.Result == RequestResult.Success)
                {
                    // Tweet posted successfully!
                }
                else
                {
                    // Something bad happened
                }
            } catch // Very silent
            {

            }
        }
コード例 #12
0
ファイル: logout.aspx.cs プロジェクト: JamesConsidine/twintie
    protected void VerifyButton_Click(object sender, EventArgs e)
    {
        ResultLabel.Visible = true;

        OAuthTokens tokens = new OAuthTokens()
        {
            AccessToken = AKTextBox.Text,
            AccessTokenSecret = ASTextBox.Text,
            ConsumerKey = CKTextBox.Text,
            ConsumerSecret = CSTextBox.Text
        };

        TwitterResponse<TwitterErrorDetails> twitterResponse = TwitterAccount.EndSession(tokens, null);

        if (twitterResponse.Result == RequestResult.Success)
        {
            ResultLabel.Text = string.Format("Success! Verified as {0}", twitterResponse.ResponseObject.ErrorMessage);
            ResultLabel.CssClass = "ResultLabelSuccess";
        }
        else
        {
            ResultLabel.Text = string.Format("Failed! \"{0}\"", twitterResponse.ErrorMessage ?? "Not Authorized.");
            ResultLabel.CssClass = "ResultLabelFailed";
        }
    }
コード例 #13
0
ファイル: TwittManager.cs プロジェクト: Pripman/TwitterApp
        /*Retrieve a twitt user from a given screen name, see https://dev.twitter.com/docs/api/1/get/users/show*/
        public static TwittUser GetTwittUser(string screenName)
        {
            OAuthTokens tokens = new OAuthTokens();
            tokens.ConsumerKey = "Removed from github example";
            tokens.ConsumerSecret = "Removed from github example";
            tokens.AccessToken = "Removed from github example";
            tokens.AccessTokenSecret = "Removed from github example";

            var list = new List<string>();

            LookupUsersOptions options = new LookupUsersOptions(){UseSSL = true, APIBaseAddress="http://api.twitter.com/1.1/"};
            options.ScreenNames.Add(screenName);

            TwitterResponse<TwitterUserCollection> res = TwitterUser.Lookup(tokens, options);
            TwitterUserCollection users = res.ResponseObject;
            TwitterUser user = users.First();

            if (user == null) return null;

            TwittUser tu = new TwittUser(
                user.Id.ToString(),
                user.Name,
                user.ScreenName,
                user.Location,
                user.Description);
            return tu;
        }
コード例 #14
0
ファイル: TwittManager.cs プロジェクト: Pripman/TwitterApp
        public static List<TwittStatus> GetTwittStatusList(string screenName)
        {
            OAuthTokens tokens = new OAuthTokens();
            tokens.ConsumerKey = "zPY6AwGePUOWAk0fTvrhZhgzg";
            tokens.ConsumerSecret = "VzBhawh55oWWocdDrn4MdLfSPcG5ypf7scFJZGrSyWkSuJAjDA";
            tokens.AccessToken = "50022775-djO15EBUOMT76TXswKa0XvwfDmM12Xo27NZmxyhwr";
            tokens.AccessTokenSecret = "QqpnD1Mq4AEQYW48NyauzAMDRGDyQ0QCTQjWNRFyFCZkz";

            var list = new List<TwittStatus>();

            UserTimelineOptions options = new UserTimelineOptions();
            options.APIBaseAddress = "https://api.twitter.com/1.1/";
            options.Count = 20;
            options.UseSSL = true;
            options.ScreenName = screenName;
            var resp = TwitterTimeline.UserTimeline (tokens, options);
            TwitterStatusCollection tweets = resp.ResponseObject;

            if (tweets == null) return null;

            foreach (var status in tweets) {
                TwittStatus ts = new TwittStatus (
                    status.Id.ToString (),
                    status.Text,
                    status.User.Id.ToString(),
                    status.CreatedDate.ToString());
                list.Add (ts);
            }
            return list;
        }
コード例 #15
0
        //
        // GET: /Home/
        public string AjaxSaveToDB()
        {
            if (Session["LoggedASP"] != null)
            {
                TimelineOptions options = new TimelineOptions();

                options.Count = 200;
                options.IncludeRetweets = true;

                OAuthTokens token = new OAuthTokens();
                token.ConsumerKey = ConfigurationManager.AppSettings["consumerKey"];
                token.ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"];
                token.AccessToken = ((User)Session["LoggedUser"]).TwitterToken;
                token.AccessTokenSecret = ((User)Session["LoggedUser"]).TwitterTokenSecret;

                TwitterResponse<TwitterStatusCollection> truc = TwitterTimeline.HomeTimeline(token, options);

                TweetEntity tweetEntity = new TweetEntity();

                tweetEntity.RemoveTweetFromOwner(((User)Session["LoggedUser"]).ID);

                foreach (var item in truc.ResponseObject)
                {
                    //int lol = ;

                    tweetEntity.AddTweet(item.Id, item.Text, item.User.ScreenName, item.User.ProfileImageLocation, ((User)Session["LoggedUser"]).ID, ((int)((TimeSpan)(item.CreatedDate - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime())).TotalSeconds));
                }
                return "Success";
            }
            else
                return "Fail";
        }
コード例 #16
0
        public void Start()
        {
            //TileService.Add<TwitterView>(new TileData
            //{
            //    Title = "Peeps",
            //    BackgroundImage = new Uri("pack://siteoforigin:,,,/Resources/Tiles/MB_0005_weather1.png")
            //});

            Task.Factory.StartNew(() =>
            {
                OAuthTokens tokens = new OAuthTokens();
                tokens.AccessToken = "478840940-tgD2Fp5NWXpDPGWyrHTxIjroDODe6F9r8JEkabQ";
                tokens.AccessTokenSecret = "Jo4fgjtkYBPTfyuigi3slqOo7lVer7rLXwj6rWs";
                tokens.ConsumerKey = "O6MTEfpHhHfhnBr4PuVmlw";
                tokens.ConsumerSecret = "lDZgfovK9FEtn8MBsTpGPn8WvuTbGal2yBD4kHLgI";

                StreamOptions options = new StreamOptions();
                Stream = new TwitterStream(tokens, "v1", options);
                Stream.StartUserStream(Friends,
                                       Stopped,
                                       Created,
                                       Deleted,
                                       DirectMessageCreated,
                                       DirectMessageDeleted,
                                       Callback);
                Radio.CurrentTrackChanged += RadioOnCurrentTrackChanged;
            })
            .ContinueWith(task =>
            {
                if (task.Exception != null)
                {
                    Logger.Log(task.Exception.ToString(), Category.Exception, Priority.Medium);
                }
            });
        }
コード例 #17
0
        /// <summary>
        /// Gets last 20 users
        /// </summary>
        /// <param name="search">Search string</param>
        /// <returns>TwitterUserInfo list</returns>
        public List <TwitterUserInfo> FindUsers(string search)
        {
            const int pageRowCount = 20;
            const int pageNumber   = 0;

            try
            {
                Twitterizer.OAuthTokens tokens = GetOAuthTokens();

                UserSearchOptions options = new UserSearchOptions();
                options.Page          = pageNumber;
                options.NumberPerPage = pageRowCount;

                TwitterResponse <TwitterUserCollection> userResponse = TwitterUser.Search(tokens, search, options);
                if (userResponse.Result == RequestResult.Success)
                {
                    TwitterUserCollection collection = userResponse.ResponseObject;
                    return(MapUsers(userResponse.ResponseObject));
                }
                else
                {
                    throw CreateException(userResponse.Result, userResponse.ErrorMessage);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw;
            }
        }
コード例 #18
0
ファイル: Tweeter.cs プロジェクト: anlcan/coapp.org
        public Tweeter(string twitterHandle) {
            try {
                var twitterKey = CloudConfigurationManager.GetSetting("twitter-key");
                var twitterSecret = CloudConfigurationManager.GetSetting("twitter-secret");
                var accessToken = CloudConfigurationManager.GetSetting(twitterHandle + "-access-token");
                var accessSecret = CloudConfigurationManager.GetSetting(twitterHandle + "-access-secret");

                if (!string.IsNullOrEmpty(twitterKey) && !string.IsNullOrEmpty(twitterSecret) && !string.IsNullOrEmpty(accessToken) && !string.IsNullOrEmpty(accessSecret)) {
                    tokens = new OAuthTokens {
                        ConsumerKey = twitterKey,
                        ConsumerSecret = twitterSecret,
                        AccessToken = accessToken,
                        AccessTokenSecret = accessSecret

                    };
                }
            }
            catch {
                throw new ConsoleException("Unable to authenticate '{0}'", twitterHandle);
            }

            if (tokens == null) {
                throw new ConsoleException("Unable to authenticate '{0}'", twitterHandle);
            }
        }
コード例 #19
0
ファイル: OAuthController.cs プロジェクト: Sironfoot/T3ME
        public ActionResult Callback(string oauth_token, string oauth_verifier, bool popup = false)
        {
            OAuthTokenResponse tokens = OAuthUtility.GetAccessToken(
                App.ConsumerKey, App.ConsumerSecret, oauth_token, oauth_verifier);

            OAuthTokens oauthTokens = new OAuthTokens();
            oauthTokens.AccessToken = tokens.Token;
            oauthTokens.AccessTokenSecret = tokens.TokenSecret;
            oauthTokens.ConsumerKey = App.ConsumerKey;
            oauthTokens.ConsumerSecret = App.ConsumerSecret;

            TwitterUser user = TwitterUser.Show(oauthTokens, tokens.UserId).ResponseObject;

            Tweeter tweeter = TweeterRepository.FromTwitterId((long)user.Id);

            if (tweeter != null)
            {
                tweeter = Mapper.Map<TwitterUser, Tweeter>(user, tweeter);
            }
            else
            {
                tweeter = Mapper.Map<TwitterUser, Tweeter>(user);
                TweeterRepository.Save(tweeter);
            }

            string secureCode = SecurityUtils.GenerateSecureKey(KeyStrength._512bit);

            HttpCookie loginCookie = new HttpCookie("Login_Cookie");

            loginCookie.Values["ID"] = tweeter.TwitterId.ToString();
            loginCookie.Values["Code"] = secureCode;
            loginCookie.Expires = DateTime.UtcNow.AddDays(30.0);
            loginCookie.HttpOnly = true;

            Response.Cookies.Add(loginCookie);

            PersistentLogin login = new PersistentLogin(tweeter);
            login.SecureKey = secureCode;
            login.LastLoginDate = DateTime.UtcNow;
            tweeter.PersistentLogins.Add(login);

            TweeterRepository.Save(tweeter);

            Tweeter = tweeter;

            if (!popup)
            {
                string referrerUrl = GetTempReferrerUrl();
                if (!String.IsNullOrWhiteSpace(referrerUrl))
                {
                    return Redirect(referrerUrl);
                }

                return RedirectToAction("Latest", "Display");
            }
            else
            {
                return View("Complete", Tweeter);
            }
        }
コード例 #20
0
ファイル: Twitter.cs プロジェクト: thewindev/CoLiW
 public Twitter(string consumerKey, string consumerSecret)
 {
     ConsumerKey = consumerKey;
     ConsumerSecret = consumerSecret;
     LoginForm = new TwitterLoginForm();
     LoginForm.Browser.Navigated += BrowserNavigated;
     Tokens = new OAuthTokens {ConsumerKey = consumerKey, ConsumerSecret = consumerSecret};
 }
コード例 #21
0
ファイル: TwitterClient.cs プロジェクト: allanckw/GEMS-Web
 static TwitterClient()
 {
     tokens = new OAuthTokens();
     tokens.ConsumerKey = "TJsNENXQpENdbZfu7REPNQ";
     tokens.ConsumerSecret = "BzsNUP8sFKXOZRBOy1q2s7erBFJRqwQPPGvtRBAl02I";
     tokens.AccessToken = "985961396-EmkCjiJFqQJ8KYv2IUY8lnpA9fLj76F9192t57HO";
     tokens.AccessTokenSecret = "PRMnstfw3DVAXRpWpR4EIzoBeTfqwnTmkXkZnDrgDA";
 }
コード例 #22
0
ファイル: Twitter.cs プロジェクト: RoxasShadow/Memes-Viewer
 public Twitter(string[] token)
 {
     tokens = new OAuthTokens();
     tokens.ConsumerKey = token[0];
     tokens.ConsumerSecret = token[1];
     tokens.AccessToken = token[2];
     tokens.AccessTokenSecret = token[3];
 }
コード例 #23
0
        /// <summary>
        /// Returns the 20 most recent statuses posted by the authenticating user. It is also possible to request another user's timeline by using the screen_name or user_id parameter.
        /// </summary>
        /// <param name="tokens">The oauth tokens.</param>
        /// <param name="options">The options.</param>
        /// <returns>
        /// A <see cref="TwitterStatusCollection"/> instance.
        /// </returns>
        public static TwitterResponse<TwitterStatusCollection> UserTimeline(
            OAuthTokens tokens,
            UserTimelineOptions options)
        {
            Commands.UserTimelineCommand command = new Commands.UserTimelineCommand(tokens, options);

            return Core.CommandPerformer.PerformAction(command);
        }
コード例 #24
0
ファイル: Program.cs プロジェクト: kavallo/twitter.GetFriends
 static Program()
 {
     _tokens = new OAuthTokens
     {
         ConsumerKey = Settings.Default.ConsumerKey,
         ConsumerSecret = Settings.Default.ConsumerSecret
     };
 }
コード例 #25
0
 public static OAuthTokens getTokens(TwUser usr)
 {
     var tokens = new Twitterizer.OAuthTokens();
     tokens.AccessToken = usr.Token;
     tokens.AccessTokenSecret = usr.TokenSecret;
     tokens.ConsumerKey = ConfigurationManager.AppSettings["consumerkey"];
     tokens.ConsumerSecret = ConfigurationManager.AppSettings["consumersecret"];
     return tokens;
 }
コード例 #26
0
        /// <summary>
        /// Sends a twitter message
        /// </summary>
        /// <param name="twitterProfile">User to send to</param>
        /// <param name="twitterUsername">Twitter username</param>
        /// <param name="body">Message to send</param>
        public bool SendTwitterMessage(string twitterProfile, string twitterUsername, string body)
        {
            var ownerSettings = EngineContext.Current.Resolve<OwnerSettings>();
            var siteSettings = EngineContext.Current.Resolve<SiteSettings>();

            // Convert the profile if to a decimal
            decimal profileId;
            decimal.TryParse(twitterProfile, out profileId);

            // Build the token object required to send the tweets
            var tokens = new OAuthTokens
            {
                AccessToken = ownerSettings.TwitterAccessToken,
                AccessTokenSecret = ownerSettings.TwitterAccessTokenSecret,
                ConsumerKey = siteSettings.TwitterConsumerKey,
                ConsumerSecret = siteSettings.TwitterConsumerSecret
            };

            try
            {
                // If we have a profile id, try sending the user a direct message
                // This will fail if the user isn't following us
                if (profileId > 0)
                {
                    var directResponse = TwitterDirectMessage.Send(tokens, profileId, body);
                    if (directResponse.Result == RequestResult.Success)
                        return true;
                }

                // Direct message failed
                // Fall back to sending a tweet containing a mention
                string tweetMessage = (!string.IsNullOrEmpty(twitterUsername) ? "@" + twitterUsername + " " : "") + body;
                if (!tweetMessage.Contains(siteSettings.TwitterHashTag))
                    tweetMessage += " " + siteSettings.TwitterHashTag;

                var mentionResponse = TwitterStatus.Update(tokens, tweetMessage);

                // If the tweet was send, jump out
                if (mentionResponse.Result == RequestResult.Success)
                    return true;

                // If the tweet failed because it's duplicate, jump out
                if (mentionResponse.Result == RequestResult.Unauthorized && mentionResponse.ErrorMessage == "Status is a duplicate.")
                    return true;

                // If we've reached this point, something has gone wrong, log the error
                var logger = EngineContext.Current.Resolve<ILogService>();
                logger.Error(string.Format("Error sending message via twitter. {0}", mentionResponse.Result + " - " + mentionResponse.ErrorMessage));
            }
            catch (Exception ex)
            {
                var logger = EngineContext.Current.Resolve<ILogService>();
                logger.Error(string.Format("Error sending message via twitter. {0}", ex.Message), ex);
            }

            return false;
        }
コード例 #27
0
ファイル: HypeBotTwitter.cs プロジェクト: qwv4851/HypeBot
        public HypeBotTwitter()
        {
            tokens = new OAuthTokens();

            tokens.ConsumerKey = Program.GetConfig("consumerKey");
            tokens.ConsumerSecret = Program.GetConfig("consumerSecret");
            tokens.AccessToken = Program.GetConfig("accessToken");
            tokens.AccessTokenSecret = Program.GetConfig("accessTokenSecret");
        }
コード例 #28
0
        /// <summary>
        /// Get an twitter OAuthToken for authentication
        /// </summary>
        /// <param name="twitterAccount">Account instance to get the token from</param>
        /// <returns>Twitterizer.OAuthTokens with the account token</returns>
        public static Twitterizer.OAuthTokens getTwitterAuthToken(Account twitterAccount)
        {
            Twitterizer.OAuthTokens authToken = new Twitterizer.OAuthTokens();
            authToken.AccessToken       = twitterAccount.getOption("accessTokenToken");
            authToken.AccessTokenSecret = ConfigurationManager.AuthenticatedUser.Decrypt(twitterAccount.getOption("accessTokenSecret"));
            authToken.ConsumerKey       = Properties.Settings.Default.TwitterConsumerKey;
            authToken.ConsumerSecret    = Properties.Settings.Default.TwitterConsumerSecret;

            return(authToken);
        }
コード例 #29
0
        internal static void UpdateStatus(string newStatusMessage, string accessToken, string accessTokenSecret)
        {
            OAuthTokens tokens = new OAuthTokens();
            tokens.AccessToken = accessToken;
            tokens.AccessTokenSecret = accessTokenSecret;
            tokens.ConsumerKey = consumerKey;
            tokens.ConsumerSecret = consumerSecret;

            TwitterStatus.Update(tokens, newStatusMessage);
        }
コード例 #30
0
ファイル: JGFBFTwitter.svc.cs プロジェクト: mattbryer/JGFBF
        public OAuthTokens GetOAuthTokens()
        {
            OAuthTokens tokens = new OAuthTokens();
            tokens.ConsumerKey = ConfigurationManager.AppSettings.Get("ConsumerKey");
            tokens.ConsumerSecret = ConfigurationManager.AppSettings.Get("ConsumerSecret");
            tokens.AccessToken = ConfigurationManager.AppSettings.Get("AccessToken");
            tokens.AccessTokenSecret = ConfigurationManager.AppSettings.Get("AccessTokenSecret");

            return tokens;
        }
コード例 #31
0
        public void RunCommand()
        {
            OAuthTokens oauth = new OAuthTokens();
            oauth.AccessToken = AccessToken;
            oauth.AccessTokenSecret = AccessTokenSecret;
            oauth.ConsumerKey = ConsumerKey;
            oauth.ConsumerSecret = ConsumerSecret;

            TwitterResponse<TwitterStatus> response = TwitterStatus.Update(oauth, strMessage);
        }
コード例 #32
0
        public static void TestTokenValidation2()
        {
            OAuthTokens fakeTokens = new OAuthTokens
                {
                    ConsumerKey = "fake",
                    ConsumerSecret = "fake"
                };

            TwitterStatus.Update(fakeTokens, "This shouldn't work");
        }
コード例 #33
0
        public static OAuthTokens getTokens(TwUser usr)
        {
            var tokens = new Twitterizer.OAuthTokens();

            tokens.AccessToken       = usr.Token;
            tokens.AccessTokenSecret = usr.TokenSecret;
            tokens.ConsumerKey       = ConfigurationManager.AppSettings["consumerkey"];
            tokens.ConsumerSecret    = ConfigurationManager.AppSettings["consumersecret"];
            return(tokens);
        }
コード例 #34
0
        /// <summary>
        /// Gets the tokens.
        /// </summary>
        /// <returns></returns>
        public static OAuthTokens GetTokens()
        {
            OAuthTokens tokens = new OAuthTokens();
            tokens.AccessToken = ConfigurationManager.AppSettings["AccessToken"];
            tokens.AccessTokenSecret = ConfigurationManager.AppSettings["AccessTokenSecret"];
            tokens.ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"];
            tokens.ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"];

            return tokens;
        }
コード例 #35
0
        // Class that will return the authentication
        protected OAuthTokens GenerateAuthentication()
        {
            var newAuth = new OAuthTokens();

            newAuth.ConsumerKey = TwitterAppData.app_consumer_key;
            newAuth.ConsumerSecret = TwitterAppData.app_consumerSecret;
            newAuth.AccessToken = TwitterAppData.app_token;
            newAuth.AccessTokenSecret = TwitterAppData.app_TokenSecret;

            return newAuth;
        }
コード例 #36
0
        /// <summary>
        /// Loads specified user information
        /// </summary>
        /// <param name="userID">Twitter user ID</param>
        /// <returns>TwitterUserInfo obect</returns>
        public TwitterUserInfo LoadUserInfo(decimal userID)
        {
            try
            {
                Twitterizer.OAuthTokens tokens = GetOAuthTokens();

                TwitterResponse <TwitterUser> userResponse = TwitterUser.Show(tokens, userID);
                if (userResponse.Result == RequestResult.Success)
                {
                    return(MapUser(userResponse.ResponseObject));
                }

                else
                {
                    throw CreateException(userResponse.Result, userResponse.ErrorMessage);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw;
            }
        }
コード例 #37
0
 /// <summary>
 /// List the lists the specified user has been added to.
 /// </summary>
 /// <param name="tokens">The tokens.</param>
 /// <param name="username">The userid.</param>
 /// <param name="options">The options.</param>
 /// <returns>
 /// A <see cref="TwitterListCollection"/> instance.
 /// </returns>
 public static TwitterResponse <TwitterListCollection> GetMemberships(OAuthTokens tokens, decimal userid, ListMembershipsOptions options)
 {
     Commands.ListMembershipsCommand command = new Twitterizer.Commands.ListMembershipsCommand(tokens, userid, options);
     return(Core.CommandPerformer.PerformAction(command));
 }
コード例 #38
0
 /// <summary>
 /// Returns the members of the specified list.
 /// </summary>
 /// <param name="tokens">The tokens.</param>
 /// <param name="username">The username.</param>
 /// <param name="listIdOrSlug">The list id or slug.</param>
 /// <returns>A collection of users as <see cref="TwitterUserCollection"/>.</returns>
 /// <remarks></remarks>
 public static TwitterResponse <TwitterUserCollection> GetMembers(OAuthTokens tokens, string username, string listIdOrSlug)
 {
     return(GetMembers(tokens, username, listIdOrSlug, null));
 }
コード例 #39
0
 /// <summary>
 /// List the lists the specified user has been added to.
 /// </summary>
 /// <param name="tokens">The tokens.</param>
 /// <param name="username">The userid.</param>
 /// <returns>
 /// A <see cref="TwitterListCollection"/> instance.
 /// </returns>
 public static TwitterResponse <TwitterListCollection> GetMemberships(OAuthTokens tokens, decimal userid)
 {
     return(GetMemberships(tokens, userid, null));
 }
コード例 #40
0
 /// <summary>
 /// Returns the 20 most recent retweets posted by the authenticating user's friends.
 /// </summary>
 /// <param name="tokens">The tokens.</param>
 /// <param name="options">The options.</param>
 /// <returns>A <see cref="TwitterStatusCollection"/> instance.</returns>
 public static TwitterResponse <TwitterStatusCollection> RetweetedToMe(OAuthTokens tokens, TimelineOptions options)
 {
     return(CommandPerformer.PerformAction(
                new Commands.RetweetedToMeCommand(tokens, options)));
 }
コード例 #41
0
 /// <summary>
 /// Shows Related Results of a tweet. Requires the id parameter of the tweet you are getting results for.
 /// </summary>
 /// <param name="tokens">The tokens.</param>
 /// <param name="statusId">The status id.</param>
 /// <param name="options">The options. Leave null for defaults.</param>
 /// <returns>A <see cref="Status"/> representing the newly created tweet.</returns>
 public static async Task <TwitterResponse <TwitterRelatedTweetsCollection> > RelatedResultsShowAsync(decimal statusId, OAuthTokens tokens, OptionalProperties options = null)
 {
     return(await Core.CommandPerformer.PerformAction(new Commands.RelatedResultsCommand(tokens, statusId, options)));
 }
コード例 #42
0
        /// <summary>
        /// Show tweet timeline for members of the specified list.
        /// </summary>
        /// <param name="tokens">The tokens.</param>
        /// <param name="username">The username.</param>
        /// <param name="listIdOrSlug">The list id or slug.</param>
        /// <param name="options">The options.</param>
        /// <returns>
        /// A <see cref="TwitterStatusCollection"/> instance.
        /// </returns>
        public static TwitterResponse <TwitterStatusCollection> GetStatuses(OAuthTokens tokens, string username, string listIdOrSlug, ListStatusesOptions options)
        {
            Commands.ListStatusesCommand command = new Twitterizer.Commands.ListStatusesCommand(tokens, username, listIdOrSlug, options);

            return(Core.CommandPerformer.PerformAction(command));
        }
コード例 #43
0
        /// <summary>
        /// Subscribes the specified tokens.
        /// </summary>
        /// <param name="tokens">The tokens.</param>
        /// <param name="listId">The list id.</param>
        /// <param name="optionalProperties">The optional properties.</param>
        /// <returns></returns>
        public static TwitterResponse <TwitterList> Subscribe(OAuthTokens tokens, decimal listId, OptionalProperties optionalProperties)
        {
            Commands.CreateListMembershipCommand command = new Commands.CreateListMembershipCommand(tokens, listId, optionalProperties);

            return(CommandPerformer.PerformAction(command));
        }
コード例 #44
0
 /// <summary>
 /// Check if a user is a member of the specified list.
 /// </summary>
 /// <param name="tokens">The tokens.</param>
 /// <param name="ownerUsername">The username of the list owner.</param>
 /// <param name="listId">The list id.</param>
 /// <param name="userId">The user id.</param>
 /// <returns>
 /// The user's details, if they are a member of the list, otherwise <c>null</c>.
 /// </returns>
 public static TwitterResponse <TwitterUser> CheckMembership(OAuthTokens tokens, string ownerUsername, string listId, decimal userId)
 {
     return(CheckMembership(tokens, ownerUsername, listId, userId, null));
 }
コード例 #45
0
 /// <summary>
 /// Returns the 20 most recent retweets posted by the authenticating user's friends.
 /// </summary>
 /// <param name="tokens">The tokens.</param>
 /// <returns>
 /// A <see cref="TwitterStatusCollection"/> instance.
 /// </returns>
 public static TwitterResponse <TwitterStatusCollection> RetweetedToMe(OAuthTokens tokens)
 {
     return(RetweetedToMe(tokens, null));
 }
コード例 #46
0
 /// <summary>
 /// Returns the 20 most recent mentions (status containing @username) for the authenticating user.
 /// </summary>
 /// <param name="tokens">The tokens.</param>
 /// <returns>
 /// A <see cref="TwitterStatusCollection"/> instance.
 /// </returns>
 public static TwitterResponse <TwitterStatusCollection> Mentions(OAuthTokens tokens)
 {
     return(Mentions(tokens, null));
 }
コード例 #47
0
        /// <summary>
        /// Returns the members of the specified list.
        /// </summary>
        /// <param name="tokens">The tokens.</param>
        /// <param name="username">The username.</param>
        /// <param name="listIdOrSlug">The list id or slug.</param>
        /// <param name="options">The options.</param>
        /// <returns>
        /// A collection of users as <see cref="TwitterUserCollection"/>.
        /// </returns>
        public static TwitterResponse <TwitterUserCollection> GetMembers(OAuthTokens tokens, string username, string listIdOrSlug, GetListMembersOptions options)
        {
            Commands.GetListMembersCommand command = new Twitterizer.Commands.GetListMembersCommand(tokens, username, listIdOrSlug, options);

            return(CommandPerformer.PerformAction(command));
        }
コード例 #48
0
 /// <summary>
 /// Returns up to 100 of the first retweets of a given tweet.
 /// </summary>
 /// <param name="tokens">The tokens.</param>
 /// <param name="statusId">The status id.</param>
 /// <param name="options">The options. Leave null for defaults.</param>
 /// <returns>
 /// A <see cref="TwitterStatusCollection"/> instance.
 /// </returns>
 public static async Task <TwitterResponse <TwitterStatusCollection> > RetweetsAsync(decimal statusId, OAuthTokens tokens, RetweetsOptions options = null)
 {
     return(await Core.CommandPerformer.PerformAction(new Commands.RetweetsCommand(tokens, statusId, options)));
 }
コード例 #49
0
        /// <summary>
        /// Removes the specified member from the list. The authenticated user must be the list's owner to remove members from the list.
        /// </summary>
        /// <param name="tokens">The tokens.</param>
        /// <param name="ownerUsername">The username of the list owner.</param>
        /// <param name="listId">The list id.</param>
        /// <param name="userIdToAdd">The user id to add.</param>
        /// <param name="options">The options.</param>
        /// <returns>
        /// A <see cref="TwitterList"/> representing the list the user was added to, or <c>null</c>.
        /// </returns>
        public static TwitterResponse <TwitterList> RemoveMember(OAuthTokens tokens, string ownerUsername, string listId, decimal userIdToAdd, OptionalProperties options)
        {
            Commands.RemoveListMemberCommand command = new Twitterizer.Commands.RemoveListMemberCommand(tokens, ownerUsername, listId, userIdToAdd, options);

            return(CommandPerformer.PerformAction(command));
        }
コード例 #50
0
 /// <summary>
 /// Returns the 20 most recent statuses posted by the authenticating user. It is also possible to request another user's timeline by using the screen_name or user_id parameter.
 /// </summary>
 /// <param name="tokens">The oauth tokens.</param>
 /// <returns>
 /// A <see cref="TwitterStatusCollection"/> instance.
 /// </returns>
 public static TwitterResponse <TwitterStatusCollection> UserTimeline(
     OAuthTokens tokens)
 {
     return(UserTimeline(tokens, null));
 }
コード例 #51
0
        /// <summary>
        /// Unsubscribes the authenticated user from the specified list.
        /// </summary>
        /// <param name="tokens">The tokens.</param>
        /// <param name="listId">The list id.</param>
        /// <param name="optionalProperties">The optional properties.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static TwitterResponse <TwitterList> UnSubscribe(OAuthTokens tokens, decimal listId, OptionalProperties optionalProperties)
        {
            Commands.DestroyListSubscriber command = new Commands.DestroyListSubscriber(tokens, listId, optionalProperties);

            return(CommandPerformer.PerformAction(command));
        }
コード例 #52
0
        /// <summary>
        /// List the lists the specified user follows.
        /// </summary>
        /// <param name="tokens">The tokens.</param>
        /// <param name="userName">Name of the user.</param>
        /// <param name="options">The options.</param>
        /// <returns>
        /// A <see cref="TwitterListCollection"/> instance.
        /// </returns>
        public static TwitterResponse <TwitterListCollection> GetSubscriptions(OAuthTokens tokens, string userName, GetListSubscriptionsOptions options)
        {
            Commands.GetListSubscriptionsCommand command = new Twitterizer.Commands.GetListSubscriptionsCommand(tokens, userName, options);

            return(Core.CommandPerformer.PerformAction(command));
        }
コード例 #53
0
 /// <summary>
 /// List the lists the specified user has been added to.
 /// </summary>
 /// <param name="tokens">The tokens.</param>
 /// <param name="username">The screenname.</param>
 /// <returns>
 /// A <see cref="TwitterListCollection"/> instance.
 /// </returns>
 public static TwitterResponse <TwitterListCollection> GetMemberships(OAuthTokens tokens, string screenname)
 {
     return(GetMemberships(tokens, screenname, null));
 }
コード例 #54
0
 /// <summary>
 /// Updates the authenticating user's status. A status update with text identical to the authenticating user's text identical to the authenticating user's current status will be ignored to prevent duplicates.
 /// </summary>
 /// <param name="tokens">The tokens.</param>
 /// <param name="text">The status text.</param>
 /// <param name="options">The options. Leave null for defaults.</param>
 /// <returns>
 /// A <see cref="Status"/> object of the newly created status.
 /// </returns>
 public static async Task <TwitterResponse <Status> > UpdateAsync(string text, OAuthTokens tokens, StatusUpdateOptions options = null)
 {
     return(await Core.CommandPerformer.PerformAction(new Commands.UpdateStatusCommand(tokens, text, options)));
 }
コード例 #55
0
 /// <summary>
 /// Subscribes the specified tokens.
 /// </summary>
 /// <param name="tokens">The tokens.</param>
 /// <param name="listId">The list id.</param>
 /// <returns></returns>
 public static TwitterResponse <TwitterList> Subscribe(OAuthTokens tokens, decimal listId)
 {
     return(Subscribe(tokens, listId, null));
 }
コード例 #56
0
 /// <summary>
 /// Updates the authenticating user's status. A status update with text identical to the authenticating user's text identical to the authenticating user's current status will be ignored to prevent duplicates.
 /// </summary>
 /// <param name="tokens">The tokens.</param>
 /// <param name="text">The status text.</param>
 /// <param name="fileData">The file to upload, as a byte array.</param>
 /// <param name="options">The options. Leave null for defaults.</param>
 /// <returns>
 /// A <see cref="Status"/> object of the newly created status.
 /// </returns>
 public static async Task <TwitterResponse <Status> > UpdateWithMediaAsync(string text, byte[] fileData, OAuthTokens tokens, StatusUpdateOptions options = null)
 {
     return(await Core.CommandPerformer.PerformAction(new Commands.UpdateWithMediaCommand(tokens, text, fileData, options)));
 }
コード例 #57
0
        /// <summary>
        /// Deletes the specified list. Must be owned by the authenticated user.
        /// </summary>
        /// <param name="tokens">The tokens.</param>
        /// <param name="username">The username.</param>
        /// <param name="listIdOrSlug">The list id or slug.</param>
        /// <param name="options">The options.</param>
        /// <returns>A <see cref="TwitterList"/> instance.</returns>
        public static TwitterResponse <TwitterList> Delete(OAuthTokens tokens, string username, string listIdOrSlug, OptionalProperties options)
        {
            Commands.DeleteListCommand command = new Twitterizer.Commands.DeleteListCommand(tokens, username, listIdOrSlug, options);

            return(Core.CommandPerformer.PerformAction(command));
        }
コード例 #58
0
        /// <overloads>
        /// Returns the 20 most recent statuses, including retweets, posted by the authenticating user and that user's friends. This is the equivalent of /timeline/home on the Web.
        /// </overloads>
        /// <param name="tokens">The tokens.</param>
        /// <param name="options">The options.</param>
        /// <returns>A collection of <see cref="TwitterStatus"/> items.</returns>
        public static TwitterResponse <TwitterStatusCollection> HomeTimeline(OAuthTokens tokens, TimelineOptions options)
        {
            Commands.HomeTimelineCommand command = new Commands.HomeTimelineCommand(tokens, options);

            return(Core.CommandPerformer.PerformAction(command));
        }
コード例 #59
0
 /// <summary>
 /// List the lists the specified user follows.
 /// </summary>
 /// <param name="tokens">The tokens.</param>
 /// <param name="userName">Name of the user.</param>
 /// <returns>
 /// A <see cref="TwitterListCollection"/> instance.
 /// </returns>
 public static TwitterResponse <TwitterListCollection> GetSubscriptions(OAuthTokens tokens, string userName)
 {
     return(GetSubscriptions(tokens, userName, null));
 }
コード例 #60
0
 /// <summary>
 /// Removes the specified member from the list. The authenticated user must be the list's owner to remove members from the list.
 /// </summary>
 /// <param name="tokens">The tokens.</param>
 /// <param name="ownerUsername">The username of the list owner.</param>
 /// <param name="listId">The list id.</param>
 /// <param name="userIdToAdd">The user id to add.</param>
 /// <returns>
 /// A <see cref="TwitterList"/> representing the list the user was added to, or <c>null</c>.
 /// </returns>
 public static TwitterResponse <TwitterList> RemoveMember(OAuthTokens tokens, string ownerUsername, string listId, decimal userIdToAdd)
 {
     return(RemoveMember(tokens, ownerUsername, listId, userIdToAdd, null));
 }