2013-12-08 2 views
0

현재 지정된 트 위치 TV 채널이 공중에 떠있을 때 IRC로 브로드 캐스트하는 스크립트를 사용하고 있습니다.Python JSON 디코더 오류

하지만 온라인에 연결될 때 어떤 이유로 계속 오류가 발생합니다. 그러나 오프라인이되면 완벽하게 정상적으로 작동합니다.

파이썬 코드 :

# Twitch IRC status autoupdate 
# Create an empty file called config.yml in the same directory, containing: 
# host: irc.quakenet.org 
# port: 6667 
# channels: ["#channel", "#anotherchannel"] 
# nspass: "nickserv/Q password" 
# password: "server password for BNC or private server" 
# twitch: "channelname" 

import requests 
import yaml 
from HTMLParser import HTMLParser 
from sys import stdout 

from twisted.internet import reactor, task, protocol 
from twisted.python import log 
from twisted.words.protocols import irc 
from twisted.application import internet, service 

with open('config.yml') as f: 
    config = yaml.load(f.read()) 
HOST, PORT = config['host'], config['port'] 


def munge(inp): 
    # Prevents highlight notification in most clients 
    return inp[0] + u"\u200b" + inp[1:] 


class TwitchProtocol(irc.IRCClient): 
    password = config["password"] if "password" in config else None 
    nickname = 'Twitch' 
    username = 'Twitch' 
    versionName = 'Twitch' 
    versionNum = 'v1.0' 
    realname = 'by blha303. https://gist.github.com/blha303' 
    loopcall = None 
    status = False 


    def signedOn(self): 
     for channel in self.factory.channels: 
      self.join(channel) 
     #Quakenet 
     self._send_message("auth %s %s" % (self.nickname, config["nspass"]), "Q") 
     #Nickserv 
     self._send_message("identify %s %s" % (self.nickname, config["nspass"]), "NickServ") 
     #Nickserv that doesn't support specifying a nickname 
     self._send_message("identify %s" % config["nspass"], "NickServ") 

     def restartloop(reason): 
      reason.printTraceback() 
      print "Loop crashed: " + reason.getErrorMessage() 
      self.loopcall.start(5.0).addErrback(restartloop) 
     self.loopcall = task.LoopingCall(self.getTwitchStatus) 
     self.loopcall.start(5.0).addErrback(restartloop) 

    def getTwitchStatus(self): 
     channel = config["twitch"] 
     data = requests.get("http://api.justin.tv/api/stream/list.json?channel=" + channel).json() 
     if data and not self.status: 
      fmt = "{}: {} {} ({})" 
      self.status = True 
      title = data[0]['title'] 
      playing = ("playing " + data[0]['meta_game']) if "meta_game" in data[0] else "" 
      viewers = "\x033\x02Online now!\x02\x0f " + str(data[0]["channel_count"]) + " viewer" 
      print viewers 
      viewers = viewers + "s" if not " 1 view" in viewers else viewers 
      print viewers 
      h = HTMLParser() 
      for ch in self.factory.channels: 
       self._send_message(h.unescape(fmt.format(title, munge(channel), playing, viewers)), ch) 
     elif not data and self.status: 
      self.status = False 
      for ch in self.factory.channels: 
       self._send_message("%s is now offline." % channel, ch) 


    def privmsg(self, user, channel, message): 
     nick, _, host = user.partition('!') 
     print "<%s> %s" % (nick, message) 


    def _send_message(self, msg, target, nick=None): 
     if nick: 
      msg = '%s, %s' % (nick, msg) 
     self.msg(target, msg) 
     print "<%s> %s" % (self.nickname, msg) 


class TwitchFactory(protocol.ReconnectingClientFactory): 
    protocol = TwitchProtocol 
    channels = config["channels"] 

if __name__ == '__main__': 
    reactor.connectTCP(HOST, PORT, TwitchFactory()) 
    log.startLogging(stdout) 
    reactor.run() 

elif __name__ == '__builtin__': 
    application = service.Application('Twitch') 
    ircService = internet.TCPClient(HOST, PORT, TwitchFactory()) 
    ircService.setServiceParent(application) 

하지만 그것은 트 위치 TV 채널이 오류를 줄 것이다 공기에있는 것을 발견 할 때.

Error: 
2013-12-08 22:42:12+0000 [-] Traceback (most recent call last): 
2013-12-08 22:42:12+0000 [-] File "/usr/lib/python2.7/dist-packages/twisted/internet/base.py", line 1192, in run 
2013-12-08 22:42:12+0000 [-]  self.mainLoop() 
2013-12-08 22:42:12+0000 [-] File "/usr/lib/python2.7/dist-packages/twisted/internet/base.py", line 1201, in mainLoop 
2013-12-08 22:42:12+0000 [-]  self.runUntilCurrent() 
2013-12-08 22:42:12+0000 [-] File "/usr/lib/python2.7/dist-packages/twisted/internet/base.py", line 824, in runUntilCurrent 
2013-12-08 22:42:12+0000 [-]  call.func(*call.args, **call.kw) 
2013-12-08 22:42:12+0000 [-] File "/usr/lib/python2.7/dist-packages/twisted/internet/task.py", line 218, in __call__ 
2013-12-08 22:42:12+0000 [-]  d = defer.maybeDeferred(self.f, *self.a, **self.kw) 
2013-12-08 22:42:12+0000 [-] --- <exception caught here> --- 
2013-12-08 22:42:12+0000 [-] File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 137, in maybeDeferred 
2013-12-08 22:42:12+0000 [-]  result = f(*args, **kw) 
2013-12-08 22:42:12+0000 [-] File "irctwitch.py", line 60, in getTwitchStatus 
2013-12-08 22:42:12+0000 [-]  data = requests.get("http://api.justin.tv/api/stream/list.json?channel=" + channel).json() 
2013-12-08 22:42:12+0000 [-] File "/usr/lib/python2.7/dist-packages/requests/models.py", line 651, in json 
2013-12-08 22:42:12+0000 [-]  return json.loads(self.text or self.content, **kwargs) 
2013-12-08 22:42:12+0000 [-] File "/usr/lib/python2.7/json/__init__.py", line 338, in loads 
2013-12-08 22:42:12+0000 [-]  return _default_decoder.decode(s) 
2013-12-08 22:42:12+0000 [-] File "/usr/lib/python2.7/json/decoder.py", line 365, in decode 
2013-12-08 22:42:12+0000 [-]  obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 
2013-12-08 22:42:12+0000 [-] File "/usr/lib/python2.7/json/decoder.py", line 383, in raw_decode 
2013-12-08 22:42:12+0000 [-]  raise ValueError("No JSON object could be decoded") 
2013-12-08 22:42:12+0000 [-] exceptions.ValueError: No JSON object could be decoded 
2013-12-08 22:42:12+0000 [-] Loop crashed: No JSON object could be decoded 

어떻게이 오류를 해결할 수 있습니까?

Thankies, TameTimmah

+0

JSON 이외의 것을 디코딩하려고하지 마십시오. –

+0

'채널'을 인코딩해야합니다. 예 : urllib.urlencode ({ 'channel': 채널})'. ['twisted.web.client.getPage'를 사용하여 json을 얻을 수 있습니다.] (https://gist.github.com/zed/7865274). – jfs

답변

1
2013-12-08 22:42:12+0000 [-] File "/usr/lib/python2.7/json/decoder.py", line 383, in raw_decode 
2013-12-08 22:42:12+0000 [-]  raise ValueError("No JSON object could be decoded") 
2013-12-08 22:42:12+0000 [-] exceptions.ValueError: No JSON object could be decoded 

json 모듈은 JSON 데이터 아니었다 뭔가를 디코딩하도록 요청 받았다.

2013-12-08 22:42:12+0000 [-] File "irctwitch.py", line 60, in getTwitchStatus 
2013-12-08 22:42:12+0000 [-]  data = requests.get("http://api.justin.tv/api/stream/list.json?channel=" + channel).json() 

.json()을 (를) 호출 한 것은 유효한 JSON이 아닙니다. .json()에 전화하기 전에 requests.get()의 결과를 인쇄 해보고 무슨 일이 일어나는 지보십시오.