如何让基于Tweepy的Twitter Bot实现远程自动运行?
如何让Tweepy开发的Twitter转发Bot自动运行?
我用Python的Tweepy库,凭借高级访问权限开发了一个Twitter Bot,它能转发带特定话题标签的推文。目前Bot运行正常,但每次都得手动点击“运行”才能执行转发操作。我编程经验不多,只会基础内容,是跟着在线教程做的,想请教怎么让这个Bot自动运行。
我的代码如下:
for tweet in tweepy.Cursor(api.search_tweets, q='#myhashtag OR #myhashtag2').items(15): try: print('\nHi! I found this tweet by @' + tweet.user.screen_name + '. ') tweet.retweet() print('Retweeted.') # Where sleep(10), sleep is measured in seconds. # Change 10 to amount of seconds you want to have in-between retweets. # Read Twitter's rules on automation. Don't spam! sleep(5) # Some basic error handling. Will print out why retweet failed, into your terminal. except tweepy.errors.TweepError as error: print('\nError. Couldn\'t retweet. Reason: ') print(error.reason) except StopIteration: break
方法1:无限循环+定时休眠(最简单上手)
把现有代码套进无限循环里,每次完成一轮转发后,休息一段时间再重新搜索新推文。启动后Bot会一直运行,不用手动触发。
修改后的完整代码(记得补上你的API认证部分):
import tweepy import time # 先补上你的API认证代码,比如: # consumer_key = "你的consumer key" # consumer_secret = "你的consumer secret" # access_token = "你的access token" # access_token_secret = "你的access token secret" # auth = tweepy.OAuthHandler(consumer_key, consumer_secret) # auth.set_access_token(access_token, access_token_secret) # api = tweepy.API(auth) while True: try: # 执行搜索和转发逻辑 for tweet in tweepy.Cursor(api.search_tweets, q='#myhashtag OR #myhashtag2').items(15): try: print(f'\nHi! I found this tweet by @{tweet.user.screen_name}. ') tweet.retweet() print('Retweeted.') time.sleep(5) # 每条转发间隔5秒,遵守Twitter规则别乱改 except tweepy.errors.TweepError as error: print(f'\nError. Couldn\'t retweet. Reason: {error.reason}') except StopIteration: break # 一轮转发结束后,休息30分钟再继续(可根据需求调整,别太短) print("本轮转发完成,休息30分钟...") time.sleep(1800) # 1800秒=30分钟 except Exception as e: print(f"程序出问题了:{e}") time.sleep(60) # 出错后先休息1分钟再重试
方法2:系统定时任务(不用一直开终端)
如果不想让终端一直挂着,用系统自带的定时工具,让它定期自动跑你的脚本:
- Windows:打开「任务计划程序」,新建基本任务,设置触发频率(比如每小时一次),操作选“启动程序”,路径指向你的Python.exe,参数填脚本的完整路径。
- Mac/Linux:终端输入
crontab -e,添加一行类似0 * * * * /usr/bin/python3 /你的脚本路径/bot.py,这代表每小时整点运行一次。
方法3:云服务器托管(24小时稳定运行)
想让Bot全天候在线的话,租个便宜的轻量云服务器,把代码传上去后,用nohup让脚本后台运行:
nohup python3 your_bot.py &
这样就算你关掉终端,程序也会在服务器后台一直跑着。
内容的提问来源于stack exchange,提问作者mxrdybxm
相关产品推荐
相关产品推荐

