Twitter Provides API for developers to use these API to create applications, send message in twitter, post content, post tweets etc. Twitter lets gives a monthly cap of 5,00,000 tweets to pull using the API.
Libraries
Steps
- Download tweet library (pip install tweet)
- Create a Twitter Developer account Create Account
- Go to projects and Apps in your developer account Projects and Apps
- Create an App and obtain consumer key, consumer secret, access token, access token secret
- Find the keys and access token in your twitter apps tab under keys and tokens
Python
import tweepy | |
consumer_key = "YOUR_APP_CONSUMER_KEY" | |
consumer_secret = "YOUR_APP_CONSUMER_SECRET" | |
access_token = "YOUR_APP_ACCESS_TOKEN" | |
access_token_secret = "YOUR_APP_ACCESS_TOKEN_SECRET" | |
auth = tweepy.OAuthHandler(consumer_key, consumer_secret) #create a OAuthHandler | |
auth.set_access_token(access_token, access_token_secret) #initialize tokens and keys | |
api = tweepy.API(auth) | |
recipient_name = api.get_user("TWITTER_ACCOUNT_NAME") #the account name you have to send a message to | |
recipient_id = recipient_name.id_str #get ID of that user | |
text = "This is a Direct Message." #message to be sent | |
direct_message = api.send_direct_message(recipient_id, text) |
Java
import java.io.IOException; | |
import java.util.List; | |
import java.util.concurrent.CompletableFuture; | |
import twitter4j.Twitter; | |
import twitter4j.TwitterException; | |
import twitter4j.TwitterFactory; | |
import twitter4j.auth.AccessToken; | |
import twitter4j.*; | |
public class message { | |
static String consumerKeyStr = "YOUR_APP_CONSUMER_KEY"; | |
static String consumerSecretStr = "YOUR_APP_CONSUMER_SECRET"; | |
static String accessTokenStr = "YOUR_APP_ACCESS_TOKEN" | |
static String accessTokenSecretStr = "YOUR_APP_ACCESS_TOKEN_SECRET"; | |
public static void main(String[] args) throws Throwable, IOException { | |
try { | |
Twitter twitter = new TwitterFactory().getInstance(); | |
twitter.setOAuthConsumer(consumerKeyStr, consumerSecretStr); | |
AccessToken accessToken = new AccessToken(accessTokenStr,accessTokenSecretStr); | |
twitter.setOAuthAccessToken(accessToken); | |
String text = "sup"; | |
twitter.sendDirectMessage("sreeharishar_", text); | |
} | |
catch (TwitterException te) { | |
te.printStackTrace(); | |
} | |
} | |
} |
Top comments (0)