Twitch随机断开了我的python机器人的连接。我搜索了很多,发现这是一个普遍的问题。唯一的解决方案似乎是自动重新连接。尝试过此方法,但我的知识似乎太有限,无法正常工作。
我试图关闭套接字,将其关闭,然后使用最初用于连接的相同例程进行连接。尝试了一些变体,但没有任何效果,当我尝试重新连接时,总是出现错误代码:“ Winerror 10038”
import socket
import sys
import modules.cfg
import time
irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
irc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
def connect():
'''
Connection to Twitch IRC using cfg.py
'''
irc.connect((modules.cfg.HOST,modules.cfg.PORT))
irc.send(str("PASS " + modules.cfg.PASS + "\r\n").encode("utf-8"))
irc.send(str("NICK " + modules.cfg.NICK + "\r\n").encode("utf-8"))
irc.send(str("JOIN " + modules.cfg.CHAN + "\r\n").encode("utf-8"))
irc.send(str("CAP REQ :twitch.tv/commands\r\n").encode("utf-8")) #whisper enable
irc.send(str("CAP REQ :twitch.tv/membership\r\n").encode("utf-8"))
def read_chat():
response = irc.recv(4096).decode('utf-8') #receive text
if response == "PING :tmi.twitch.tv\r\n":
print("Ping received")
irc.send("PONG :tmi.twitch.tv\r\n".encode("utf-8"))
return response
def send(msg):
try:
irc.send("PRIVMSG {} : {}\r\n".format(modules.cfg.CHAN, msg).encode("utf-8"))
except:
irc.shutdown(socket.SHUT_RDWR)
irc.close()
print("\n\nDisconnected\n")
time.sleep(10)
connect()
print("Reconnected\n\n")
我对编码非常陌生,这是我的一种业余爱好。希望有人可以帮助我!谢谢你们
答案 0 :(得分:0)
向user207421致谢,我终于找到了方法..对我来说,这有点奇怪,但是可以。
def re_connect():
irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
irc.connect((modules.cfg.HOST,modules.cfg.PORT))
irc.send(str("PASS " + modules.cfg.PASS + "\r\n").encode("utf-8"))
irc.send(str("NICK " + modules.cfg.NICK + "\r\n").encode("utf-8"))
irc.send(str("JOIN " + modules.cfg.CHAN + "\r\n").encode("utf-8"))
irc.send(str("CAP REQ :twitch.tv/commands\r\n").encode("utf-8")) #whisper enable
irc.send(str("CAP REQ :twitch.tv/membership\r\n").encode("utf-8"))
def send(msg):
try:
irc.send("PRIVMSG {} : {}\r\n".format(modules.cfg.CHAN, msg).encode("utf-8"))
except:
irc.shutdown(socket.SHUT_RDWR)
irc.close()
print("\n\nDisconnected\n")
time.sleep(10)
re_connect()
print("Reconnected\n\n")