Check if a certain user has tweeted - twitter

Is it possible to write a script for twitter that checks when the last time a certain user has tweeted?
Preferably using python.

Yes, it is possible. Here is how using TwitterAPI.
from TwitterAPI import TwitterAPI
SCREEN_NAME = 'justinbieber'
CONSUMER_KEY = 'XXXX'
CONSUMER_SECRET = 'XXXX'
ACCESS_TOKEN_KEY = 'XXXX'
ACCESS_TOKEN_SECRET = 'XXXX'
api = TwitterAPI(CONSUMER_KEY,
CONSUMER_SECRET,
ACCESS_TOKEN_KEY,
ACCESS_TOKEN_SECRET)
r = api.request('statuses/user_timeline', {'screen_name':SCREEN_NAME, 'count':1})
for item in r:
print(item['created_at'])

There is a python library for accessing the Twitter API called Tweepy
More info on the API can be found here: https://dev.twitter.com
An older post but may be relevant: streaming api with tweepy only returns second last tweet and NOT the immediately last tweet

Related

How to get a user's new Tweets with a Telegram Python bot while run_polling?

I'm currently developing a Telegram bot using telegram-python-bot and tweepy.
I want to create a feature that allows users of the bot to add their Twitter ID list via Telegram and have their new Tweets sent to them in real-time.
I want that the bot should be application.run_polling() to receive commands from the user, and at the same time, forwarding new tweets from Twitter users in users individual list.
When I read the tweepy documentation, I realized that I can get real-time tweets with fewer api requests if I fetch them through MyStream(auth=auth, listener=None).
But I don't know how to get both functions to work on the same file at the same time.
version
nest_asyncio-1.5.6 python_telegram_bot-20.0 tweepy-4.12.1
def main() -> None:
application = Application.builder().token("...").build()
add_list = ConversationHandler(
entry_points=[CallbackQueryHandler(input_id, pattern='input_id')],
states={ADD :[MessageHandler(filters.TEXT & ~filters.COMMAND, add)],},
fallbacks=[CallbackQueryHandler(button,pattern='back')])
application.add_handler(CommandHandler("on", on))
application.add_handler(add_list)
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("list", list_setting))
application.add_handler(CommandHandler("admin", admin))
application.add_handler(CommandHandler("help", help_command))
application.add_handler(CallbackQueryHandler(button))
application.run_polling()
if __name__ == "__main__":
main()
This is my main statement and I made it work until the SIGINT(ctrl+c) came in via application.run_polling().
I want to combine the above code to run and do the following at the same time.
import tweepy
consumer_key = "..." # Twitter API Key
consumer_secret = "..." # Twitter API Secret Key
access_token = "..." # Twitter Access Key
access_token_secret = "..." # Twitter Access Secret Key
usernames = ['...']
auth = tweepy.OAuth1UserHandler(
consumer_key, consumer_secret, access_token, access_token_secret
)
# Convert screen names to user IDs
user_ids = []
for username in usernames:
user = tweepy.API(auth).get_user(screen_name=username)
user_ids.append(str(user.id))
# Create a custom stream class
class MyStream(tweepy.Stream):
def __init__(self, auth, listener=None):
super().__init__(consumer_key, consumer_secret, access_token, access_token_secret)
def on_status(self, status):
tweet_url = f"https://twitter.com/{status.user.screen_name}/status/{status.id_str}"
print(f"{status.user.screen_name} tweeted: {status.text}\n{tweet_url}")
# send message to telegram
# Create a stream object with the above class and authentication
myStream = MyStream(auth=auth, listener=None)
# Start streaming for the selected users
myStream.filter(follow=user_ids)
I also tried to use thread's interval function or python-telegram-bot's job_queue.run_repeating function,
but these seem problematic for forwarding messages in real time.
I'm desperately looking for someone to help me with this😢.

Get/list all tweets of all users my account follow

I am using python tweepy to connect the twitter end point, and it's very simple to list all of any single user's tweets. It is also possible to read my account's "following" list, so technicly I can get the list of all the tweets by all of my followed users, thing is, it will be lot's and lot's of seperate API calls.
Is there a way to bulk this effectively?
You're not going to be able to get them all in one go, Twitter has rate limits to prevent that, but this script will get as many from each user as possible:
import tweepy
# Put your API keys here
CONSUMER_KEY = ""
CONSUMER_SECRET = ""
ACCESS_TOKEN = ""
ACCESS_TOKEN_SECRET = ""
# Authenticate to Tweepy and wait if you get rate limited
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True)
# For each user that you follow.....
for user in tweepy.Cursor(api.friends, screen_name="pigeonburger").items():
# Get each user's username and print out 100 of their tweets
username = user._json['screen_name']
print(api.user_timeline(screen_name = username, count = 100))
# Do what you want with those tweets after

how to get all tweets past and present with particular # tag or # tag

I am trying to make an application for an organization which will required to fetch all past as well present tweets with some particular hashtag like #airtel, #airtel etc, how should I get past tweet, I am able to fetch the present tweet with the following url : "https://api.twitter.com/1.1/search/tweets.json?q=%23airtel"
Thanks
You can get up to a maximum of 100 tweets with the twitter rest api see the following twitter documentation. The best you can do is use the count parameter https://api.twitter.com/1.1/search/tweets.json?q=%23airtel&count=100
After various search on Google I found some useful library for fetching tweets e.g:
TwitterSearch [https://github.com/ckoepp/TwitterSearch], you would I find the twitter profile # https://twitter.com/twittersearch
Tweepy [https://github.com/tweepy/tweepy], you could find more info at http://www.tweepy.org/
I have implemented using both. Tweepy implementation is as follows:
import tweepy
import json
consumer_key = "get"
consumer_secret = "From"
access_token = "Twitter"
access_token_secret = "site"
# Authenticate twitter Api
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
#made a cursor
c = tweepy.Cursor(api.search, q='%23Coursera')
c.pages(15) # you can change it make get tweets
#Lets save the selected part of the tweets inot json
tweetJson = []
for tweet in c.items():
if tweet.lang == 'en':
createdAt = str(tweet.created_at)
authorCreatedAt = str(tweet.author.created_at)
tweetJson.append(
{'tweetText':tweet.text,
'tweetCreatedAt':createdAt,
'authorName': tweet.author.name,
})
#dump the data into json format
print json.dumps(tweetJson)
If any one have problem, let me know, will provide git repo for this.
Thanks
Krishna

How to parse twitter using python and based on geolocation?

I am trying to parse the twitters on specific topic using Python. However, the code runs flawlessly but I need to add the geolocation as one of the core search criteria in parsing. Any suggestion how to do so?
Could you provide more example code?
If I'm understanding your question correctly, you could use the tweepy library. This could also be achieved using Get requests.
I'll provide a Tweepy example:
# enter twitter info from [Twitter developers site][2]
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
ACCESS_KEY = ''
ACCESS_SECRET = ''
# setup authorization
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
Location based search can be done using geocode in the tweepy.search function:
# skeleton query:
geo_based_tweets = api.search(q='some text I want to search on', geocode='long,lat,radius')
# example query about the vikings in Minneapolis:
api.search(q="vikings OR football", geocode='44.9833,-93.2667,10km', count=100)
Hope that's helpful!

Possible to tweet using appkey/secret key from a different account via twython?

I have a twitter account with an App made, currently it's setup so students can tweet from our website and as such their tweets show "via SchoolAppNameHere" at the bottom of their tweets.
Is it possible to use Twython to use the Appkey and secret key and then get auth tokens from a completely different so when I was to run the bit of code below it would tweet from an account what didn't create the app...
from twython import Twython
APP_KEY = ''
APP_SECRET = ''
OAUTH_TOKEN = ''
OAUTH_TOKEN_SECRET = ''
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
twitter.update_status(status="test")
Any ideas would be much appreciated :)
Edit, Updated example/explanation below:
Let's say the following image's are from the account "stackoverflowapp" and the app called "Stackoverflow Test App":
Using the following bit of code would tweet from the account "stackoverflowapp" with the tweet "test" via the applicationg called "Stackoverflow Test App"
from twython import Twython
APP_KEY = 'coN_kEY_123456789'
APP_SECRET = 'cOn_sEcr3t_123456789'
OAUTH_TOKEN = 'Acc3ss_tok3N_123456789'
OAUTH_TOKEN_SECRET = 'aCCeSS_tOkEn_sEcrET_123456789'
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
twitter.update_status(status="test")
Let's say that the following image is from the account "useraccount1" and the app is called "testing123":
So now that I have the access tokens to login to the account "useraccount1", how can I tweet via the app called "Stackoverflow test app" which was created by the user: "stackoverflowapp" example of what I tried is below:
from twython import Twython
APP_KEY = 'coN_kEY_123456789'
APP_SECRET = 'cOn_sEcr3t_123456789'
OAUTH_TOKEN = 'Acc3ss_123456789'
OAUTH_TOKEN_SECRET = 'aCCeSS_sEcrET_123456789'
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
twitter.update_status(status="test update")
Unfortunately, I get the error:
TwythonAuthError: Twitter API returned a 401 (Unauthorized), Could not authenticate you
This is of course, possible. When you create an application in Twitter, they give you your own authentication tokens for you to use immediately, as a convenience.
Use the access token string as your "oauth_token" and the access token secret as your "oauth_token_secret" to sign requests with your own Twitter account. Do not share your oauth_token_secret with anyone.
To get keys for other accounts for the same application, you need to request more keys for each account. This is described in detail here: https://dev.twitter.com/docs/auth/obtaining-access-tokens
Since it sounds like you're going to be doing the authorization yourself, the simpler PIN-based approach should probably be used.
You're using twython, obtaining these can be done using the library: https://twython.readthedocs.org/en/latest/usage/starting_out.html#authentication
get_authentication_tokens and get_authorized_tokens are the methods you're looking for.
from twython import Twython
import sys
APP_KEY = 'coN_kEY_123456789'
APP_SECRET = 'cOn_sEcr3t_123456789'
twitter = Twython( APP_KEY, APP_SECRET )
auth = twitter.get_authentication_tokens()
print( 'Visit %s and enter your PIN: ' % auth.get( 'auth_url' ) ),
pin = sys.stdin.readline().strip()
twitter = Twython( APP_KEY, APP_SECRET, auth.get( 'oauth_token' ), auth.get( 'oauth_token_secret' ) )
tokens = twitter.get_authorized_tokens( pin )
print( 'OAUTH_TOKEN: %s' % tokens.get( 'oauth_token' ) )
print( 'OAUTH_TOKEN_SECRET: %s' % tokens.get( 'oauth_token_secret' ) )
Store OAUTH_TOKEN and OAUTH_TOKEN_SECRET some place safe and reuse at will. Also, make sure you authorize the correct account when visiting the URL and getting the PIN.
All your API calls will be made on bahalf the account that authorized access via the tokens and your via line will be your original application. Use the appropriate tokens for each account you'd like to tweet from, it's not possible to mix and match.

Resources