回复我朋友的所有推文的 Twitter 机器人。 Python

时间:2021-05-14 14:18:22

标签: python twitter bots

您好,我正在搜索如何创建一个 Twitter 机器人,该机器人在 Python 中回复特定用户的所有推文。 我已经创建了一个开发者帐户,我是 Python 初学者。

1 个答案:

答案 0 :(得分:1)

首先,访问 https://dev.twitter.com,并创建一个新应用程序。 enter image description here enter image description here

领导你的 venv 或 anaconda 并执行

pip install tweepy

现在,在您的开发目录中,创建一个文件,keys.py,并添加以下代码:

#!/usr/bin/env python
#keys.py
#visit https://dev.twitter.com to create an application and get your keys
keys = dict(
    consumer_key =          'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    consumer_secret =       'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    access_token =          'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    access_token_secret =   'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
)

用您新创建的 Twitter 应用程序中的密钥和令牌替换“x”字段

在keys.py所在目录下创建replybot.py文件,并添加如下代码:

#!/usr/bin/env python
import tweepy
#from our keys module (keys.py), import the keys dictionary
from keys import keys

CONSUMER_KEY = keys['consumer_key']
CONSUMER_SECRET = keys['consumer_secret']
ACCESS_TOKEN = keys['access_token']
ACCESS_TOKEN_SECRET = keys['access_token_secret']

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)

twts = api.search(q="Hello World!")

#list of specific strings we want to check for in Tweets
t = ['Hello world!',
    'Hello World!',
    'Hello World!!!',
    'Hello world!!!',
    'Hello, world!',
    'Hello, World!']

for s in twt:
    for i in t:
        if i == s.text:
            sn = s.user.screen_name
            m = "@%s Hello!" % (sn)
            s = api.update_status(m, s.id)

检查您的 API 是否正常工作。 sleep 是你确保你没有被要求验证你是一个机器人 python .txt

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import tweepy, time, sys

argfile = str(sys.argv[1])

#enter the corresponding information from your Twitter application:
CONSUMER_KEY = '1234abcd...'#keep the quotes, replace this with your consumer key
CONSUMER_SECRET = '1234abcd...'#keep the quotes, replace this with your consumer secret key
ACCESS_KEY = '1234abcd...'#keep the quotes, replace this with your access token
ACCESS_SECRET = '1234abcd...'#keep the quotes, replace this with your access token secret
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)

filename=open(argfile,'r')
f=filename.readlines()
filename.close()

for line in f:
    api.update_status(line)
    time.sleep(900)#Tweet every 15 minutes

回复特定推特用户

toReply = "someonesTwitterName" #user to get most recent tweet
api = tweepy.API(auth)

#get the most recent tweet from the user
tweets = api.user_timeline(screen_name = toReply, count=1)

for tweet in tweets:
    api.update_status("@" + toReply + " This is what I'm replying with", in_reply_to_status_id = tweet.id)

你可以编写任何你想要的逻辑