python - Tweepy 4.0:“'Listener'对象没有属性'running'”错误?
问题描述
我正在尝试将基本的流式 Twitter 机器人转换为 Tweepy 4.0 alpha,以便利用一些较新的功能。但是,我什至无法开始使用描述新流协议的文档。
我已经将我的程序简化为一个测试用例,但运行它仍然会出现错误AttributeError: 'MyStreamListener' object has no attribute 'running'
。有人能指出我的问题在哪里吗?关于这个特定错误似乎没有任何其他问题,我试图密切关注文档。由于缺乏示例,我不得不做出一些猜测——例如,连接到流需要一组不同的参数,而不是连接到常规 api,因此有两个get_auth
调用——但目前我更感兴趣的是只是让它工作而不是让事情变得超级干净。
#!/usr/bin/env python3
import tweepy
import json
import configparser
import os
def _read_config():
config = configparser.ConfigParser()
script_dir = os.path.dirname(__file__)
config_file = os.path.join(script_dir, '../bot-config.ini')
config.read(config_file)
return config
def _get_api_auth(config):
auth = tweepy.OAuthHandler(
config['auth']['consumer_key'], config['auth']['consumer_secret'])
auth.set_access_token(config['auth']['token'],
config['auth']['token_secret'])
return auth
def _get_stream_auth(config):
return (config['auth']['consumer_key'], config['auth']['consumer_secret'],
config['auth']['token'], config['auth']['token_secret'])
class MyStreamListener(tweepy.Stream):
def __init__(self, stream_auth, api):
super(tweepy.Stream, self).__init__()
self._api = api
self._tweet_count = 0
def on_data(self, data):
tweet = json.loads(data)
if 'text' not in tweet:
return
self._tweet_count += 1
if tweet['truncated']:
text = tweet['extended_tweet']['full_text']
else:
text = tweet['text']
if 'Rumplestiltskin' in text:
try:
self._api.retweet(tweet['id'])
print('Tweeted id %d!', tweet['id'])
except tweepy.TweepError as err:
print('Unable to tweet %d:', tweet['id'])
print(err.reason)
if (self._tweet_count % 10000) == 0:
print('Processed %s tweets', self._tweet_count)
def run():
config = _read_config()
api_auth = _get_api_auth(config)
api = tweepy.API(api_auth)
stream_auth = _get_stream_auth(config)
twitterStream = MyStreamListener(stream_auth, api)
twitterStream.sample()
if __name__ == '__main__':
run()
解决方案
呸,这基本上只是一个简单的 Python 错误,正如 Discord 服务器中的某个人所指出的那样。我会把它留在这里,以防其他人犯同样的错误;基本上我需要单独调用所有 auth 的东西,所以调用行应该是:
twitterStream = MyStreamListener(config['auth']['consumer_key'],
config['auth']['consumer_secret'],
config['auth']['token'],
config['auth']['token_secret'],
api)
我也弄错了super
语法;它应该是:
def __init__(self, cons_key, cons_secret, token, token_sec, api):
super().__init__(cons_key, cons_secret, token, token_sec)
而已。
推荐阅读
- javascript - Youtube API 密钥配额在使用有问题的密钥之前超过了
- python - Squish 测试:通过 Squish 获取活动窗口或顶部窗口
- python - python包安装不保存?
- python - 当 pip 卸载不起作用时,如何卸载库?
- php - 从地址创建超链接
- flutter - 反转图像颜色
- mysql - Combine one table with meta data in another table
- python - 用 Pandas 列中的句点替换空格
- docker - 有没有办法在谷歌云构建的 yaml 构建配置文件中的同一步骤中分离不同的参数?
- ios - Transporter 错误 IOS 应用程序图标 1024x1024 丢失