Using twython to reply to a given tweet - python

How can I use twython to post a reply to any twitter id?
The way to post a status update on twitter by this awesome twython library is as follows -
try:
a = twitter.update_status(status=message)
return HttpResponse("1", content_type='text/plain')
except TwythonError as e:
return HttpResponse(e, content_type='text/plain')
Just wanted to know, how can I post a reply to a tweet using twython?

Assuming you have the twitter id, you can simply do add in_reply_to_status to the update_status function.
try:
a = twitter.update_status(status=message, in_reply_to_status_id=twitter_id)
return HttpResponse("1", content_type='text/plain')
except TwythonError as e:
return HttpResponse(e, content_type="'text/plain')
This can be found here.
Also, you should check out the endpoints.py in the twython package for more functions to use Twython.

Related

How do I get Tweepy to not retrieve Tweets older than a week old?

I'm attempting to build a Twitter bot that retrieves #Fortnite tweets on Twitter, and then retweets them. The problem I'm encountering is Tweepy is retrieving tweets that are very old. Is it possible to make it so it won't retrieve tweets older than a week old?
I looked that the Twitter API docs, and found since_id, Is this what I need to implement?
import tweepy
import keys
import time, datetime
auth = tweepy.OAuthHandler(keys.API_KEY, keys.API_SECRET_KEY)
auth.set_access_token(keys.ACCESS_TOKEN, keys.SECRET_ACCESS_TOKEN)
api = tweepy.API(auth)
def twitter_bot(hashtag, delay):
while True:
print(f"\n{datetime.datetime.now()}\n")
for tweets in api.search_tweets(q=hashtag, result_type="recent", count=30):
try:
tweet_id = dict(tweets._json)["id"]
tweet_text = dict(tweets._json)["text"]
print("id: " + str(tweet_id))
print("text: " + str(tweet_text))
api.retweet(tweet_id)
print("[+] Retweeted successfully!")
except tweepy.TweepyException as e:
print(e)
time.sleep(delay)
twitter_bot("#Fortnite", 480)

Retweet specific user. Tweepy & python

I have this code that retweets a tweet if that said tweet includes the mention of #oogabooga.
How would I change it so that it would retweet every tweet tweeted by #oogabooga without the need of a mention in those said tweets?
So basically I want to retweet everything that #oogabooga tweets, regardless of content. I tried modifying it myself and went through tweepy docs, API, and looked up some similar problems trying to build from there, but with no luck. Help a noob out!
import logging
import time
import random
from datetime import datetime, timedelta
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
auth = tweepy.OAuthHandler('hiddenkey1','hiddenkey2')
auth.set_access_token('hiddenkey3','hiddenkey4')
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
user = api.me()
def fav_retweet_user(api, user_handle):
search_query = f"{user_handle} -filter:retweets"
logger.info(f'Retrieving tweets mentioning {user_handle}...')
tweets = api.search(q=search_query, lang ="en")
for tweet in tweets:
if tweet.in_reply_to_status_id is not None or \
tweet.user.id == api.me().id:
return
if not tweet.favorited:
try:
tweet.favorite()
logger.info(f"Liked a tweet mentioning {user_handle}")
except Exception as e:
logger.error("Error on fav", exc_info=True)
if not tweet.retweeted:
try:
tweet.retweet()
logger.info(f"Retweeted a tweet mentioning {user_handle}")
except Exception as e:
logger.error("Error on fav and retweet", exc_info=True)
while True:
fav_retweet_user(api, "#oogabooga")
logger.info("Waiting...")
time.sleep(30)
Changing your search query to the following will work:
search_query = f"-filter:from:{user_handle}"

What can't I parse the API in my Telegram bot code?

I am trying to create a Telegram bot that allows users to search up recipes that require only ingredients that they have on-hand. It is built with Python and I have a rough code, but before I fine-tune the details, I want to get the basic form of it up and running. Unfortunately, I am facing difficulty in parsing the API for the recipes corresponding to ingredients that the user has listed in his/her message. Specifically, the logged error message is "Error parsing the API". Could someone take a look at my code and help me see what went wrong please?
This is the relevant portion of my code:
def handle_messages(messages):
for message in messages:
mappedIngreds = []
for i in range(len(message.text)):
ingred = message.text[i].lower()
if i == 0:
mappedIngreds.append(ingred)
else:
mappedIngreds.append(f"+ {ingred}")
# get responses from API
try:
response = requests.get(f"{apiURL}{mappedIngreds}{apiId}{apiKey}")
response.raise_for_status() # for debugging
except requests.RequestException:
logging.error("Error connecting to the API")
return None
# format responses into list of recipes
try:
recipes = []
for i in response.json():
recipeInfo = {}
recipeInfo["name"] = i["label"]
recipeInfo["url"] = i["url"]
recipes.append(recipeInfo)
except (KeyError, TypeError, ValueError):
logging.error("Error parsing the API")
return None
# send list of recipes to user
try:
bot.reply_to(message.chat.id, "Try these recipes:", *recipeInfo["name"], *recipeInfo["url"], sep="\n")
except:
logging.error("Error printing recipes")
My full code is here: https://pastebin.com/W0CceAt9

Twitter API: Pull Tweets by a user AND containing a keyword using Twython (Python)

I'm new to Python and Twython, and could use some help with #3. I'm doing some research and want to pull tweets by a user AND containing a certain keyword. I'd also like to have it exported to csv but figuring it out at all is the first part. Thanks :)
# Bring in the module Twython which pulls from Twitter's API
from twython import Twython, TwythonError
# Making variables for my twitter API keys
CONSUMER_KEY = 'my personal input hered'
CONSUMER_SECRET = 'my personal input here'
ACCESS_KEY = 'my personal input here'
ACCESS_SECRET = 'my personal input here'
twitter = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)
## 1) This block works and searches for tweets containing a specific keyword
print(twitter.search(q='python'))
## 2) This block works as well and returns all tweets by username
try:
user_timeline = twitter.get_user_timeline(screen_name='')
except TwythonError as e:
print e
for tweets in user_timeline:
print tweets['text']
## 3) I can't get this one to work. It is supposed to return all tweets by
# username AND containing keyword
*try:
user_timeline = twitter.get_user_timeline(screen_name='ThePSF') and twitter.search(q='lines')
except TwythonError as e:
print e
for tweets in user_timeline and q:
print tweets['text']*
The Twitter API does not allow you to search within a user timeline - you would have to do that yourself in #2.
An alternative to what you are doing in #3 is to just use the Search API (twitter.search in this case) and pass in a query that covers both cases. An example would be
twitter.search(q='from:ThePSF AND lines')
However, note that the search API is limited to 7 days of data.

YouTube python API v3 HttpError 400 subscriptionDuplicate

I'm using YouTube python API v3 to subscribe oauth2 authenticated users to new channels.
def add_subscription(youtube, channel_id):
add_subscription_response = youtube.subscriptions().insert(
part='id,snippet',
body=dict(
snippet=dict(
resourceId=dict(
channelId=channel_id
)
)
)).execute()
return add_subscription_response["id"], add_subscription_response["snippet"]["title"]
youtube = get_authenticated_service(args)
try:
subscription_id,channel_title = add_subscription(youtube, args.channel_id)
except HttpError, e:
print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
else:
print "A subscription to '%s' was added." % channel_title
From https://developers.google.com/youtube/v3/docs/subscriptions/insert it seems that (or maybe, I understood that...) if the user is already subscribed to the channel described by channel_id, the function should raise an HttpError with e.resp.status=400 for a subscriptionDuplicate.
Nevertheless, if I try to subscribe to a channel the user is already subscribed to, the function normally returns a subscription_id and channel_title.
Shouldn't it raise HttpError 400?
And, if I'm not making mistakes and this is exactly the way the function should work, what could I do to check if the authenticated user is already subscribed to channel_id using only subscriptions().insert()?
I could call subscriptions().list() before, to check if user is subscribed:
def is_subscribed(youtube, channel_id):
is_subscription_response = youtube.subscriptions().list(
part='id',
mine='true',
forChannelId=channel_id
).execute()
if len(is_subscription_response["items"]) == 0:
return False
else:
return True
But this would increase quota usage...
I also tried the Subscriptions: insert request and use it in a channel that I already subscribed and I'm not getting the error subscriptionDuplicate. I don't know why the API did not return this error.
So to answer your question about how to check if the authenticated user is already subscribed to channel_id, use the Subscriptions: list to know all the channel that you subscribed.
Here is the sample request, just replace the channelId with your own channelId.
https://www.googleapis.com/youtube/v3/subscriptions?part=snippet&channelId=YOUR_CHANNEL_ID&key={YOUR_API_KEY}

Categories

Resources