Syntax Error in trying to define a Tweepy API function - python

I'm trying to make a Twitter bot that selects a quote from a list of quotes I give it to Tweet every 2 hours. I keep having a syntax error when I try to define the Tweet daily function and I'm not exactly sure what's wrong. I'm a beginner in coding so if it's obvious, I apologize; it's my first time doing this. I already had success in having the app Tweet with the api.update_status() command but I'm not sure how to have select from the list I'm creating. I did import random, time, from datetime, import datetime, timedelta as well as tweepy and everything else successfully.
random.choices(tweets)
last_tweeted = datetime.now()-timedelta(hours=2), random.choices(tweets)
tweets = ['insert, list, of tweets, I am adding']
where python says I have a syntax code
def tweet_daily(api, last_tweeted, random.choices(tweets):
if last_tweeted < datetime.now()-timedelta(hours=2):
logger.info(f"Tweeted {tweets, random.choices} at {datetime.now().strftime('%m/%d/%Y at %H:%M:%S')}")
return datetime.now()
else:
return last_tweeted
api.update_status('tweets(random.choice)')`

You're missing a close parenthesis in the function definition:
def tweet_daily(api, last_tweeted, random.choices(tweets):

Related

Python mongodb/motor "'ObjectId' object is not iterable" error while trying to find item in collection

I know that there are similar questions, but I've tried everything that was advised and still getting an error. I'm trying to fetch item from mongo collection by id, converting string to an ObjectId, like that:
from bson import ObjectId
async def get_single_template(db, template_id):
template = await db.templates.find_one({ '_id': ObjectId(template_id) })
return template
And I'm getting an error:
ValueError: [TypeError("'ObjectId' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')]
"template_id" is a valid string, like "601401887ecf2f6153bbaaad". ObjectId created from it - too. It fails only to work inside find_one() method. When I'm using find() with that id it works well. I've tried from bson.objectid import ObjectId too - no difference. I'm using motor library to access mongo. Is there something that I'm missing?
P.S. Links to the corresponding docs:
https://pymongo.readthedocs.io/en/stable/tutorial.html#querying-by-objectid
Though I'm using motor async library, I can't find direct examples in it's docs. Basically, it wraps pymongo. I can only find examples in other's source code.
Well, I've found out what caused that issue. The problem was not in the way I've tried to query data, but in the way I've tried to return it. I've forgotten to convert ObjectId to string in the entity that I've retrieved from database and tried to return it 'as is'. My bad.
I encountered this problem as well while using Python motor for Mongodb. In your app.collection.find_one(...), add {'_id': 0} along with the dictionary which has the value you want to search for.
So it should be like this:
await app.collection.find_one({"value": val},{'_id': 0})
After long research i find one solution work for me
I try many ways let's discuss with you one of them
DATABASE_URL = mongodb://localhost:portname/yourdbname
client = mongo_client.MongoClient(
settings.DATABASE_URL#, ServerSelectionTimeoutMS=5000
)
db = client[settings.MONGO_INITDB_DATABASE]
Post = db.post
#router.get('/')
async def posts(user_id: str = Depends(oauth2.require_user)):
list = []
for i in Post.find():
list.append(i)
print("list", list)
return {'status': 'success', "list": list}
Everything work on print but when i return the response then show me error that mentioned in post i solve this error by doing this
serialize ObjectId with native fastApi methods
at top of my file i just import
from bson.objectid import ObjectId
import pydantic
pydantic.json.ENCODERS_BY_TYPE[ObjectId]=str
Note:
I am not expert of fastapi with MongoDB i just start learning last 5 days ago about fastapi and start learning mongoDb last 2 days ago. if you have any better practice then let me know
i also trying to serialize data but on that case also not work so try this way
thank you
this comment help me from github
https://github.com/tiangolo/fastapi/issues/1515#issuecomment-782838556

Trying to schedule a function using schedule library. Getting "Invalid Time Format" error

I'm trying to schedule a "job" at a time picked by user input. When trying to input the time I get a "Invalid Time format" error.
I'm a beginner and am thinking it has to do with how to work with time in python. Any guidance is greatly appreciated.
import schedule
h = what_hour()
m = what_min()
schedule.every().day.at("h:m").do(single_alarm_sound)
Try:
schedule.every().day.at(f"{h}:{m}").do(single_alarm_sound)
More on f-string formatting here: https://realpython.com/python-f-strings/
It's a very nice feature, where you can inject variables, etc right into the string.

Python Reddit Comment Keyword Search

I am building a scraper that searches reddit comments for keywords. I am having two problems
Problem 1. in order to build the commentforest I need to get the submission_id from the comment so I can pull all of the comments related to that submission.I am having trouble figuring out how to get the submission id.
problem 2. for some reason every time I run this code it gives me new comments that include the keywords (I am assuming this is just because new comments have been added) BUT some of the old comments arent showing up when i run the code again. this is supposed to pull ALL the comments that match my keyword from the subreddit what am i doing wrong?
from psaw import PushshiftAPI
from datetime import datetime, timezone, timedelta
from dateutil.relativedelta import relativedelta
api = PushshiftAPI()
comments = api.search_comments(q='OP', subreddit='askreddit')
max_response_cache = 1000
cache = []
commentcount = 0
for c in comments:
cache.append(c)
commentcount += 1
print (f' comment {commentcount}: {c.body}')
I want the code to print out the submission id related to the comments and I want to be able to pull all the comments that match my keywords.

Getting an Invalid Syntax with datetime module

I am trying to do something which should be fairly simple with the datetime module:
import sys
import datetime
from twython import Twython
CONSUMER_KEY = 'omitted'
CONSUMER_SECRET = 'omitted'
ACCESS_KEY = 'omitted'
ACCESS_SECRET = 'omitted'
api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)
time = print(datetime.datetime.now())
api.update_status(status='The power went out in the dorms again at '+time+'. Please fix. [tweeted automatically using python]')
I have chosen my time format based on the result of the 'print timenow' line however it says
File "twitterbot.py", line 12
time=print(datetime.datetime.now())
^
SyntaxError: invalid syntax
Can anyone see what I am doing wrong?
Thanks
In Python 2, print is a special language construct and not a regular function. It does not return a value, so you can't assign its return value to a variable. You probably meant:
time = datetime.datetime.now()
print(time)
(Note that it's legal in Python 2 to write print time without parentheses, but I'd advise against that. Even if you can't use Python 3 (maybe you can, though!) it's good to get into the habit of writing code in Python 3 style to ease the transition.)
In Python 3, what you wrote is syntactically valid. But print returns None, so the time variable would not have the value you want.

Python Tweepy 280 Character Statuses

I'm trying to scrape the full 280 character tweets off of twitter but I can't get them to not trail off with '...' after 140 chars. Here's my code:
import tweepy
import datetime
auth = tweepy.OAuthHandler("", "")
auth.set_access_token("", "")
api = tweepy.API(auth)
end_date = datetime.datetime.utcnow() - datetime.timedelta(days=0)
for status in api.user_timeline(targer_user):
print(status.text)
if status.created_at > end_date:
break
I've read that adding text_mode=extendedto the function will solve this, but it's making no difference for me. If I use another suggested argument tweet_mode='extended', text is no longer an attribute of status.
How can I fix this?
It seems you need to use full_text now to get the 280 char tweet. Try something along the lines of:
print(status.extended_tweet['full_text'])
The tweet_mode='extended' can be used in user_timeline if you want, in which case you would just use below:
print(status.full_text)
This looks a bit nicer to me.
It might also be worth pointing out that - from what I've read - this might not work for a retweet (Twitter streaming API not return full tweets) but there are separate bits of the api you can use for that, so be sure to check before you print.
Twitter docs, in case you want a closer look at the update: https://developer.twitter.com/en/docs/tweets/tweet-updates.html

Categories

Resources