public async void DeleteToFavoriteAndRetweet(string username, formTwitter form) { try { IList <Tweet> tweets = await twitter.TimelineOperations.GetUserTimelineAsync(username); foreach (Tweet aux in tweets) { try { if (aux.IsFavoritedByUser && aux.IsRetweetedByUser) { await twitter.TimelineOperations.DeleteStatusAsync(aux.ID); } } catch (Exception ex) { continue; } } } catch (Exception ex) { } }
//Eliminar tweet public async void eliminarTweet(string texto, formTwitter form) { try { IList <Tweet> lineaTiempo; Tweet tweet; long id = 0; lineaTiempo = twitter.TimelineOperations.GetUserTimelineAsync().Result; foreach (Tweet tweetTwitter in lineaTiempo) { if (Convert.ToString(tweetTwitter.Text).Split(new string[] { " https" }, StringSplitOptions.None)[0] == texto.Replace("\r", "")) { id = tweetTwitter.ID; } } if (lineaTiempo.First(x => x.ID == id) != null) { tweet = await twitter.TimelineOperations.DeleteStatusAsync(id); } } catch (Exception error) { form.txtLog.Text = System.DateTime.Now + " " + "Error al enviar tweet: " + error.Message + Environment.NewLine + form.txtLog.Text; } }
public void generarTweets(List <AutomaticMessageModel> tweetsAutomatics, formTwitter form) { try { while (true) { string resultado = ""; Random rnd = new Random(); int i = rnd.Next(tweetsAutomatics.Count); if (tweetsAutomatics[i].Status == 1 && tweetsAutomatics[i].State == 1) { this.enviarTweet(tweetsAutomatics[i].Tweet, form, Convert.ToString(tweetsAutomatics[i].Id)); tweetsAutomatics[i].Status = 0; form.bdSQLite.updateStatus(tweetsAutomatics[i], ref resultado); form.construirTabla(ref resultado); break; } else if (tweetsAutomatics[i].Status == 0 && tweetsAutomatics[i].State == 1) { this.eliminarTweet(tweetsAutomatics[i].Tweet, form); tweetsAutomatics[i].Status = 1; form.bdSQLite.updateStatus(tweetsAutomatics[i], ref resultado); form.construirTabla(ref resultado); break; } } } catch (Exception ex) { } }
public async void FollowToFollows(string username, formTwitter form) { try { Random rnd4 = new Random(); CursoredList <TwitterProfile> twitterp = await twitter.FriendOperations.GetFollowersAsync(username); string resultado = ""; foreach (TwitterProfile tp in twitterp) { try { if (form.txtUsuarioAccesoTwitter.Text != tp.ScreenName) { await twitter.FriendOperations.FollowAsync(tp.ID); List <Cuentas> cuentas = new List <Cuentas>(); form.bdSQLite.obtenerCuentas(ref resultado, ref cuentas); var valor = cuentas.Find(x => x.Username == Convert.ToString(tp.ScreenName)); if (valor == null) { Cuentas cuenta = new Cuentas(); cuenta.Username = tp.ScreenName; cuenta.Status = 1; int i4 = rnd4.Next(10000); if (i4 % 2 == 0) { cuenta.Follow = true; } else { cuenta.Follow = false; } form.bdSQLite.insertarCuenta(ref form.tareasTwitter, cuenta, ref resultado); } else { resultado = System.DateTime.Now + " " + "La cuenta ya se encuentra registrado."; form.txtLog.Text = System.DateTime.Now + " " + resultado + Environment.NewLine + form.txtLog.Text; } } } catch (Exception ex) { continue; } } form.construirTablaCuentas(ref resultado); } catch (Exception ex) { } }
public async void UnFollow(string username, formTwitter form) { try { await twitter.FriendOperations.UnfollowAsync(username); } catch (Exception ex) { } }
public async void enviarTweet(string texto, formTwitter form) { try { Tweet tweet = await twitter.TimelineOperations.UpdateStatusAsync(texto); } catch (Exception error) { form.txtLog.Text = System.DateTime.Now + " " + "Error al enviar tweet: " + error.Message + Environment.NewLine + form.txtLog.Text; } }
public async void UnFollowTwenttyNoFollow(formTwitter form) { string resultado = ""; try { form.btTest_Aux(); form.UnFollow_Aux(); } catch (Exception ex) { } }
//Conectar con API de Twitter mediante PIN para obtener token de acceso //devuelve true si la conexión se ha realizado correctamente public bool obtenerTokenTwitter(ref string resultado, formTwitter form) { try { var auth = new SingleUserAuthorizer { CredentialStore = new SingleUserInMemoryCredentialStore { ConsumerKey = form.consumer_key, ConsumerSecret = form.consumer_secret, AccessToken = form.access_token, AccessTokenSecret = form.access_token_secret } }; context = new TwitterContext(auth); TwitterServiceProvider twitterServiceProvider = new TwitterServiceProvider(form.consumer_key, form.consumer_secret); // Autenticación en Twitter usando código PIN OAuthToken oauthToken = twitterServiceProvider.OAuthOperations.FetchRequestTokenAsync("oob", null).Result; string authenticateUrl = twitterServiceProvider.OAuthOperations.BuildAuthorizeUrl(oauthToken.Value, null); System.Diagnostics.Process.Start(authenticateUrl); string pinCode = ""; InputBox.solicitarTexto("Código PIN", "Introduzca el código PIN obtenido de Twitter:", ref pinCode); // Step 3 - Exchange the Request Token for an Access Token string verifier = pinCode; // <-- This is input into your application by your user AuthorizedRequestToken requestToken = new AuthorizedRequestToken(oauthToken, pinCode); OAuthToken oauthAccessToken = twitterServiceProvider.OAuthOperations.ExchangeForAccessTokenAsync(requestToken, null).Result; twitter = twitterServiceProvider.GetApi(oauthAccessToken.Value, oauthAccessToken.Secret); resultado = System.DateTime.Now + " " + "Conectado a API de twitter correctamente con PIN"; return(true); } catch (Exception error) { resultado = System.DateTime.Now + " " + "Error al obtener token acceso Twitter: " + error.Message; return(false); } }
public void generarRetweetFavoritos(List <Cuentas> cuentas, formTwitter form) { try { while (true && (cuentas.Find(x => x.Autorizar == true) != null || cuentas.Find(x => x.Favorites == true) != null)) { string resultado = ""; Random rnd = new Random(); int i = rnd.Next(cuentas.Count); if (cuentas[i].Autorizar || cuentas[i].Favorites) { if (cuentas[i].Status == 1 && cuentas[i].State == 1) { this.AddToFavoriteAndRetweet(cuentas[i].Username, form); cuentas[i].Status = 0; form.bdSQLite.updateStatusSeguidores(cuentas[i], ref resultado); form.construirTablaCuentas(ref resultado); break; } else if (cuentas[i].Status == 0 && cuentas[i].State == 1) { this.DeleteToFavoriteAndRetweet(cuentas[i].Username, form); //this.UnFollow(cuentas[i].Username, form); cuentas[i].Status = 1; form.bdSQLite.updateStatusSeguidores(cuentas[i], ref resultado); form.construirTablaCuentas(ref resultado); break; } } } } catch (Exception ex) { } }
public void generarSeguidores(List <Cuentas> cuentas, formTwitter form) { try { while (true && cuentas.Find(x => x.Follow == true) != null) { string resultado = ""; Random rnd = new Random(); int i = rnd.Next(cuentas.Count); if (cuentas[i].Follow) { if (cuentas[i].Status == 1 && cuentas[i].State == 1) { this.FollowToFollows(cuentas[i].Username, form); cuentas[i].Status = 0; form.bdSQLite.updateStatusSeguidores(cuentas[i], ref resultado); form.construirTablaCuentas(ref resultado); break; } else if (cuentas[i].Status == 0 && cuentas[i].State == 1) { this.UnFollow(cuentas[i].Username, form); cuentas[i].Status = 1; form.bdSQLite.updateStatusSeguidores(cuentas[i], ref resultado); this.UnFollowTwenttyNoFollow(form); form.construirTablaCuentas(ref resultado); break; } } } } catch (Exception ex) { } }
//crear la BD SQLite y las tablas para guardar datos de Twitter public void crearBDSQLite(string fichero, string contrasena, ref string resultado, formTwitter form) { try { //si existe el fichero de BD creamos las tablas if (!System.IO.File.Exists(fichero)) { //creamos la BD SQLite SQLiteConnection.CreateFile(fichero); if (contrasena != "") { //establecemos la contraseña conexionSQLite = new SQLiteConnection("Data Source=" + fichero + ";Version=3;Password="******";"); } //conectamos con la BD SQLite para crear las tablas string resultadoConexion = ""; if (conectarBDSQLite(fichero, contrasena, ref resultadoConexion)) { //crear las tablas de SQLite para guardar datos de Twitter //tabla images string consultaSQL = "create table image (" + "id integer primary key autoincrement, url text, tweetid integer)"; SQLiteCommand comandoSQL = new SQLiteCommand(consultaSQL, conexionSQLite); comandoSQL.CommandType = CommandType.Text; comandoSQL.ExecuteNonQuery(); //tabla images consultaSQL = "create table video (" + "id integer primary key autoincrement, url text, tweetid integer)"; comandoSQL = new SQLiteCommand(consultaSQL, conexionSQLite); comandoSQL.CommandType = CommandType.Text; comandoSQL.ExecuteNonQuery(); //tabla usuarios consultaSQL = "create table cuentas (" + "id long not null primary key, usuario text, status text, fecha datetime, state integer, seguir integer, favoritos integer, autorizar integer)"; comandoSQL = new SQLiteCommand(consultaSQL, conexionSQLite); comandoSQL.CommandType = CommandType.Text; comandoSQL.ExecuteNonQuery(); //tabla seguidores consultaSQL = "create table seguidores (" + "id long not null primary key, fecha datetime)"; comandoSQL = new SQLiteCommand(consultaSQL, conexionSQLite); comandoSQL.CommandType = CommandType.Text; comandoSQL.ExecuteNonQuery(); //tabla amigos consultaSQL = "create table amigos (" + "id long not null primary key, fecha datetime)"; comandoSQL = new SQLiteCommand(consultaSQL, conexionSQLite); comandoSQL.CommandType = CommandType.Text; comandoSQL.ExecuteNonQuery(); //tabla mensajes directos consultaSQL = "create table mensaje (" + "id not null primary key, idusuario long)"; comandoSQL = new SQLiteCommand(consultaSQL, conexionSQLite); comandoSQL.CommandType = CommandType.Text; comandoSQL.ExecuteNonQuery(); //tabla amigos consultaSQL = "create table tweets (" + "id long not null primary key, tweet text, status integer, fecha datetime, state integer, idCuenta integer)"; comandoSQL = new SQLiteCommand(consultaSQL, conexionSQLite); comandoSQL.CommandType = CommandType.Text; comandoSQL.ExecuteNonQuery(); foreach (string username in form.listUsers) { if (username != form.txtUsuarioAccesoTwitter.Text) { consultaSQL = "insert into cuentas (id,usuario,status,fecha,state,seguir,favoritos,autorizar) values ((select count(*) from cuentas),@usuario,@status,@fecha,@state,@seguir,@favoritos,@autorizar)"; SQLiteParameter parametroUsuario = new SQLiteParameter(); parametroUsuario.ParameterName = "@usuario"; parametroUsuario.DbType = DbType.String; parametroUsuario.Value = Convert.ToString(username); SQLiteParameter parametroStatus = new SQLiteParameter(); parametroStatus.ParameterName = "@status"; parametroStatus.DbType = DbType.String; parametroStatus.Value = Convert.ToString(1); SQLiteParameter parameterFecha = new SQLiteParameter(); parameterFecha.ParameterName = "@fecha"; parameterFecha.DbType = DbType.DateTime; parameterFecha.Value = DateTime.Now; SQLiteParameter parametroState = new SQLiteParameter(); parametroState.ParameterName = "@state"; parametroState.DbType = DbType.Int32; parametroState.Value = Convert.ToInt32("1"); SQLiteParameter parametroSeguir = new SQLiteParameter(); parametroSeguir.ParameterName = "@seguir"; parametroSeguir.DbType = DbType.Int32; parametroSeguir.Value = Convert.ToInt32("0"); SQLiteParameter parametroFavoritos = new SQLiteParameter(); parametroFavoritos.ParameterName = "@favoritos"; parametroFavoritos.DbType = DbType.Int32; parametroFavoritos.Value = Convert.ToInt32("1"); SQLiteParameter parametroAutorizar = new SQLiteParameter(); parametroAutorizar.ParameterName = "@autorizar"; parametroAutorizar.DbType = DbType.Int32; parametroAutorizar.Value = Convert.ToInt32("1"); comandoSQL = new SQLiteCommand(consultaSQL, conexionSQLite); comandoSQL.CommandType = CommandType.Text; comandoSQL.Parameters.Add(parametroUsuario); comandoSQL.Parameters.Add(parametroStatus); comandoSQL.Parameters.Add(parameterFecha); comandoSQL.Parameters.Add(parametroState); comandoSQL.Parameters.Add(parametroSeguir); comandoSQL.Parameters.Add(parametroFavoritos); comandoSQL.Parameters.Add(parametroAutorizar); comandoSQL.ExecuteNonQuery(); } } resultado = System.DateTime.Now + " " + "BD SQLite creada correctamente."; } else { if (contrasena != "") { //establecemos la contraseña conexionSQLite = new SQLiteConnection("Data Source=" + fichero + ";Version=3;Password="******";"); resultado = System.DateTime.Now + " " + "Conectado a la BD SQLite correctamente"; } } } } catch (Exception error) { resultado = System.DateTime.Now + " " + "Error al abrir la BD SQLite: " + error.Message; } }
//Enviar tweet public async void enviarTweet(string texto, formTwitter form, string tweetid) { try { string resultado = ""; Random rnd = new Random(); Tweet tweet; List <string> listImagen = new List <string>(); form.bdSQLite.obtenerImagen(ref resultado, ref listImagen, tweetid); List <Task <Media> > imageUploadTasks = new List <Task <Media> >(); List <string> listVideo = new List <string>(); form.bdSQLite.obtenerVideos(ref resultado, ref listVideo, tweetid); List <Task <Media> > videoUploadTasks = new List <Task <Media> >(); if (listImagen.Count > 0 || listVideo.Count > 0) { int i = rnd.Next(10000); if (i % 2 == 0) { foreach (var image in listImagen) { imageUploadTasks.Add(context.UploadMediaAsync(File.ReadAllBytes(image), "image/jpg", "tweet_image")); } await Task.WhenAll(imageUploadTasks); var mediaIds = (from tsk in imageUploadTasks select tsk.Result.MediaID) .ToList(); await context.TweetAsync( texto, mediaIds ); } else { Media media = null; foreach (var video in listVideo) { media = await context.UploadMediaAsync(File.ReadAllBytes(video), "video/mp4", "tweet_video"); } Media mediaStatusResponse = null; do { if (mediaStatusResponse != null) { int checkAfterSeconds = mediaStatusResponse?.ProcessingInfo?.CheckAfterSeconds ?? 0; Console.WriteLine($"Twitter video testing in progress - waiting {checkAfterSeconds} seconds."); await Task.Delay(checkAfterSeconds * 1000); } mediaStatusResponse = await (from stat in context.Media where stat.Type == MediaType.Status && stat.MediaID == media.MediaID select stat) .SingleOrDefaultAsync(); } while (mediaStatusResponse?.ProcessingInfo?.State == MediaProcessingInfo.InProgress); if (mediaStatusResponse?.ProcessingInfo?.State == MediaProcessingInfo.Succeeded) { Status tweett = await context.TweetAsync(texto, new ulong[] { media.MediaID }); if (tweett != null) { Console.WriteLine($"Tweet sent: {tweett.Text}"); } } else { MediaError error = mediaStatusResponse?.ProcessingInfo?.Error; if (error != null) { form.txtLog.Text = System.DateTime.Now + " " + "Error al enviar tweet: " + "Request failed - Code: {error.Code}, Name: {error.Name}, Message: {error.Message}" + Environment.NewLine + form.txtLog.Text; } } } } else { tweet = await twitter.TimelineOperations.UpdateStatusAsync(texto); } } catch (Exception error) { form.txtLog.Text = System.DateTime.Now + " " + "Error al enviar tweet: " + error.Message + Environment.NewLine + form.txtLog.Text; } }