Reddit更新后(> 2个月前)我的机器人将不再运行

时间:2014-08-11 05:31:06

标签: python beautifulsoup reddit praw

这是返回的错误:

    /usr/lib/python3.2/platform.py:381: ResourceWarning: unclosed file <_io.TextIOWrapper name='/etc/lsb-release' mode='rU' encoding='UTF-8'>
  full_distribution_name=0)
Version 2.1.15 of praw is outdated. Version 2.1.18 was released 4 days ago.
/usr/local/lib/python3.2/dist-packages/requests/packages/urllib3/connection.py:99: DeprecationWarning: the 'strict' argument isn't supported anymore; http.client now always assumes HTTP/1.x compliant servers.
  HTTPConnection.__init__(self, host, port, strict, timeout, source_address)
^C
^C
Traceback (most recent call last):
  File "stocksbot.py", line 21, in <module>
    r.login('stocksBot', '******')
  File "/usr/local/lib/python3.2/dist-packages/praw/__init__.py", line 1186, in login
    self.request_json(self.config['login'], data=data)
  File "/usr/local/lib/python3.2/dist-packages/praw/decorators.py", line 161, in wrapped
    return_value = function(reddit_session, *args, **kwargs)
  File "/usr/local/lib/python3.2/dist-packages/praw/__init__.py", line 499, in request_json
    response = self._request(url, params, data)
  File "/usr/local/lib/python3.2/dist-packages/praw/__init__.py", line 371, in _request
    response = handle_redirect()
  File "/usr/local/lib/python3.2/dist-packages/praw/__init__.py", line 344, in handle_redirect
    timeout=timeout, **kwargs)
  File "/usr/local/lib/python3.2/dist-packages/praw/handlers.py", line 135, in wrapped
    result = function(cls, **kwargs)
  File "/usr/local/lib/python3.2/dist-packages/praw/handlers.py", line 54, in wrapped
    return function(cls, **kwargs)
  File "/usr/local/lib/python3.2/dist-packages/praw/handlers.py", line 90, in request
    allow_redirects=False)
  File "/usr/local/lib/python3.2/dist-packages/requests/sessions.py", line 486, in send
    r = adapter.send(request, **kwargs)
  File "/usr/local/lib/python3.2/dist-packages/requests/adapters.py", line 330, in send
    timeout=timeout
  File "/usr/local/lib/python3.2/dist-packages/requests/packages/urllib3/connectionpool.py", line 480, in urlopen
    body=body, headers=headers)
  File "/usr/local/lib/python3.2/dist-packages/requests/packages/urllib3/connectionpool.py", line 285, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "/usr/lib/python3.2/http/client.py", line 967, in request
    self._send_request(method, url, body, headers)
  File "/usr/lib/python3.2/http/client.py", line 1005, in _send_request
    self.endheaders(body)
  File "/usr/lib/python3.2/http/client.py", line 963, in endheaders
    self._send_output(message_body)
  File "/usr/lib/python3.2/http/client.py", line 808, in _send_output
    self.send(msg)
  File "/usr/lib/python3.2/http/client.py", line 746, in send
    self.connect()
  File "/usr/local/lib/python3.2/dist-packages/requests/packages/urllib3/connection.py", line 136, in connect
    timeout=self.timeout,
  File "/usr/lib/python3.2/socket.py", line 386, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):

同样,这是我的代码(它的非常非常一起被黑了):

# Reddit bot made for /r/stocks.  Summon with '$' followed by the ticker symbol.  
# Created by /u/chuiy

#import Python Reddit API Wrapper
import socket
from threading import Lock
import praw
from praw import *
#Allows us to print from a dictionary
from pprint import pprint
from requests import *
from bs4 import BeautifulSoup
import time
import os.path

alreadyDone = open('done.txt', 'a+')

user_agent = "/u/StocksBot created by /u/chuiy"

r = praw.Reddit(user_agent=user_agent)
r.login('stocksBot', '******')
ownName = "stocksBot"

while True:
        try:
                sub = r.get_subreddit('stocksBot')
                #set subReddit
                comments = praw.helpers.comment_stream(r, sub, limit=200)
                #Retrieves 200 comments from the subReddit
                for comment in comments:
                        if "$$" in comment.body and comment.id not in alreadyDone.read() and comment.author.name != ownName:
                        #if /u/stocksBot finds $$ in the post, the comment is new, and the name does not match ours
                                position = comment.body.index('$')
                                #find position of first $.  Temporary hack.
                                start = position + 2 #find first character of ticker symbol
                                end = start + 4 #find last character
                                symbolList = []
                                for letter in comment.body[start:end]:
                                        symbolList.append(letter)

                                symbol = ''.join(str(e) for e in symbolList if e.isalpha()) #turn list of letters in symbol into string
                                symbol.strip()
                                response = requests.get("http://finance.yahoo.com/q?s=" + symbol, stream=False)

#get HTML from custom URL
                                summaryPage = requests.get("http://finance.yahoo.com/q/pr?s=" + symbol, stream=False)
                                c = response.content
                                d = summaryPage.content
                                soup = BeautifulSoup(c)
                                soup1 = BeautifulSoup(d)
                                try:
                                        result = soup.find_all('td', {'class' : 'yfnc_tabledata1'}) #extract data from table
                                        name = soup.find_all('div', {'class' : 'title'}) #get title
                                        getSummary = soup1.find_all('p') #get Business Summary
                                        stockInfo=(
                                        name[0].text +' \n\n'
                                        '\n\n'
                                        '**Prev Close**:  ' + result[0].text + '     **Open**:  ' + result[1].text + '     **Bid**:  ' + result[2].text + '     **Ask**:  ' + result[3].text + '     **1y Target Est**:  ' + result[4].text + ' **Beta**:  ' + result[5].text + '\n\n'
                                        '**Next Earnings Date**:  ' + result[6].text + '     **Days Range**:  ' + result[7].text + '     **52 wk Range**:  ' + result[8].text + '     **Volume**:  ' + result[9].text + '     **Avg Vol (3m)**:  ' + result[10].text + '\n\n'
                                        '**Market Cap**:  ' + result[11].text + '     **P/E (ttm)**:  ' + result[12].text + '     **EPS (ttm)**:  ' + result[13].text + '     **Div & Yield**:  ' + result[14].text + '\n\n'
                                        '\n\n'
                                        '\n\n'
                                        '-------------------------------------------------------------------------------------------------------------\n\n'
                                        '\n\n'
                                        '**Brief Summary**\n\n'
                                        + getSummary[6].text[:450] + '...\n\n'
                                        '-------------------------------------------------------------------------------------------------------------\n\n'
                                        'Hi, I\'m /u/stocksBot. Summon me with "$$" immeditely followed by the ticker symbol and I will reply with information about the stock.  \n\n'
                                        'Created by /u/chuiy.'
                                        )
                                        alreadyDone.write(comment.id)
                                        #add comment.id to the set alreadyDone
                                        comment.reply(stockInfo) #reply to the comment
                                        time.sleep(15) #wait five minutes, prevents raising praw.errors.RateLimitExceeded
                                except IndexError:
                                        couldNotFind = (
                                        'Sorry, I could not find information for the symbol you provided.  If you believe this is an error, contact /u/chuiy.'
                                        )
                                        alreadyDone.write(comment.id)
                                        comment.reply(couldNotFind)
        except praw.errors.RateLimitExceeded as error:
                print("Sleeping %d seconds" % error.sleep_time)
                time.sleep(error.sleep_time)

我真的不知道可能导致此错误的原因。我尝试过更新praw(因为它说它已经过时了),但我没有运气。如果有人能指出我出错的地方,甚至纠正我,我都会非常感激。我的机器人运行2-3个月前;但我停止支付VPS服务并将其下线。现在我想让它重新启动并运行,但我遇到了排除故障的问题。我可能只是以更明智的OOP方式重写整个事情,但我想查看Stack Overflow社区,看看是否有人可以提供一些建议。

谢谢!

1 个答案:

答案 0 :(得分:0)

这里没有错误。您收到两个警告:ResourceWarning和DeprecationWarning。你可以放心地忽略这两个。

回溯仅仅是由于你的终端按ctrl + c而提前终止程序。