【发布时间】:2021-12-14 15:19:27
【问题描述】:
我正在编写一个 Twitter 机器人,使用 Tweepy 转发具有特定关键字的推文。
使用is_not_a_reply 方法,我尝试只转发不回复另一条推文的推文。它几乎 99% 的时间都能正常工作,但很少有一些回复仍然被转发。
我真的不知道我的代码有什么问题!!!
import os
import tweepy
from dotenv import load_dotenv
# take environment variables from .env.
load_dotenv()
# get environment variables for Twitter API
consumer_key = os.environ.get("CONSUMER_KEY")
consumer_secret = os.environ.get("CONSUMER_SECRET")
access_token = os.environ.get("ACCESS_TOKEN")
access_token_secret = os.environ.get("ACCESS_TOKEN_SECRET")
def twitter_api_authenticate():
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
return tweepy.API(auth, wait_on_rate_limit=True)
class MyStream(tweepy.Stream):
def __init__(
self, consumer_key, consumer_secret, access_token, access_token_secret
):
super().__init__(
consumer_key, consumer_secret, access_token, access_token_secret
)
self.twitterApi = twitter_api_authenticate()
# when a new tweet is posted on Twitter with my filtered keywords
def on_status(self, status):
# If the found tweet is not a reply to another tweet
if self.is_not_a_reply(status):
# Retweet the found tweet (status)
self.retweet(status)
# Like the found tweet (status)
self.like(status)
def retweet(self, status):
# Retweet the tweet
self.twitterApi.retweet(status.id)
def like(self, status):
# Like the tweet
self.twitterApi.create_favorite(status.id)
def is_not_a_reply(self, status):
if status.in_reply_to_status_id == None:
return True
else:
return False
if __name__ == "__main__":
trackList = ["Keyword1", "Keyword2"]
stream = MyStream(
consumer_key, consumer_secret, access_token, access_token_secret
)
stream.filter(track=trackList, languages=["fa"])
Tweepy version: 4.1.0
Python version: 3.8.10
【问题讨论】:
-
请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。
-
你确定这些推文是回复,而不仅仅是提及的推文吗?您能否提供其中一条推文的示例?
-
@Harmon758 是的,我确定他们是回复。无论如何,我刚才发现我的错误,那些推文本身不是回复,而是回复的转推!现在我应该检查过滤后的推文是否是转发的回复。
标签: python twitter bots tweepy twitterapi-python