I get Winerror 10038 when i try to reconnect - python

Twitch randomly disconnects my python bot. I googled a lot and found out that this is a common problem. Only solution seems to be an automated reconnect. Tried this, but my knowledge seems to be way too limited to make it work.
I tried to shut down the socket, close it and then use the same routine to connect that i initially use to connect. Tried a few variations, but nothing worked i Always get the Error-Code: "Winerror 10038" when i try to re-connect
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")
I am pretty new to coding and it´s some kind of a hobby of mine. Hopefully someone can help me! Thank you guys

Thx to user207421 i finally found the way.. for me it is a bit strange, but it works.
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")

Related

Dealing with HTTPS CONNECT requests

I'm writing a really simple web proxy through python and right now I'm working on dealing with HTTPS CONNECT requests so I can open HTTPS websites. I'm trying to set up an SSL tunnel but my code is just not quite right. I think I'm close but if someone could take a look and push me in the right direction that would be great. My current understanding of what I'm supposed to do is
Recognize that the request is a CONNECT request
Send a message back to the browser as I have defined in the variable connect_req in my code
That's about it
Here's my code:
def ProxyThread(conn, client_addr):
request = conn.recv(MAX_BUFFER)
#print request
# Parsing
method, webserver, port = ParseReq(request)
print 'Request = ' + method + ' ' + webserver + ':' + str(port) + '\n'
try:
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.connect((webserver, port))
if method == 'CONNECT':
connect_req = 'HTTP/1.1 200 Connection established\r\n'
connect_req += 'Proxy-agent: localhost\r\n\r\n'
conn.send(connect_req.encode())
serverSocket.send(connect_req)
while 1:
data = serverSocket.recv(MAX_BUFFER)
# while there is data to receive from server
if len(data) > 0:
conn.send(data)
else:
break
serverSocket.close()
conn.close()
except socket.error, (message):
print message
if conn:
conn.close()
if serverSocket:
serverSocket.close()
return
Edit 1: Updated code to start a thread when I get a HTTPS req
def ProxyThread(conn, client_addr):
request = conn.recv(MAX_BUFFER)
method, webserver, port = ParseReq(request)
#Handle index out of range exception - Throw out the request
if method is None or webserver is None or port is -1:
return
print 'Request = ' + method + ' ' + webserver + ':' + str(port) + ' START\n'
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
if method == 'CONNECT':
connect_req = 'HTTP/1.0 200 Connection established\r\n'
connect_req += 'Proxy-agent: ProxyServer/1.0\r\n'
connect_req += '\r\n'
print connect_req
conn.send(connect_req)
thread = threading.Thread(target=HTTPSProxyThread, args=(conn, serverSocket))
thread.start()
serverSocket.connect((webserver, port))
serverSocket.send(request)
while 1:
data = serverSocket.recv(MAX_BUFFER)
# while there is data to receive from server
if len(data) > 0:
conn.send(data)
else:
break
print 'Request = ' + method + ' ' + webserver + ':' + str(port) + ' FINISH\n'
serverSocket.close()
conn.close()
def HTTPSProxyThread(conn, serverSocket):
while 1:
request = conn.recv(MAX_BUFFER)
print request
method, webserver, port = ParseReq(request)
serverSocket.connect((webserver, port))
serverSocket.send(request)
while 1:
data = serverSocket.recv(MAX_BUFFER)
# while there is data to receive from server
if len(data) > 0:
conn.send(data)
else:
break
A lot of people seem to be building their own web proxies in Python, or Node.js these days.
As someone who has spent the past 22 years making a web proxy, I wonder why people do it to themselves, especially where there is free product available on all the main platforms where somebody has already dealt with the issues such as (some of these you will have to deal with later)
tunneling (CONNECT)
chunking
HTTP authentication
Funky non-compliant behaviour from a surprising number of servers and clients.
performance
scalability
logging
caching
policy framework and enforcement
etc
Whilst it's a fun way to pass the time for a while, the more of these proxies there are out there, the more broken the web becomes overall if the naive implementations are used for more general traffic. If you're just using this for your own specific deployment requirement, the ignore this comment.
I guess the point I'm trying to make is that making a well-behaved (let alone performant) web proxy is non-trivial.

python: IRC bot involunteer infinity loop

I've coded this python irc bot for twitch, and i have an issue:
after an average of 20 minutes without messages to read, the bot send in the prompt an infinity of useless messages, and the bot can't work, even if there is messsages to read (and after a few hours, the hosting machine crash... because of the place that it takes in RAM).
I putted here the code... If you know a way to transform the receiving line to an event or something else...
-*- coding: utf-8 -*-
import socket
import sys
import time
CHANNEL = "#twitch" #actually I tested my bot on an other channel, where I've the admins rights
s = socket.socket()
def connection():
print("connecting...")
s.connect(("irc.chat.twitch.tv", 6667))
print("identifing...")
s.send("PASS " + "oauth:*****************************" + "\r\n") #i censured for evident security reason
s.send("NICK " + "mistercraft" + "\r\n")
print("joining channel " + CHANNEL)
s.send("JOIN " + CHANNEL + "\r\n")
print("Connected")
def send(Message):
s.send("PRIVMSG "+CHANNEL+" :"+ Message + "\r\n")
print("Sent : " + Message)
connection()
send("Hello world !!!")
while 1:
text = ""
recu = s.recv(2040) #receive line, where there is the issue
if len(recu.split(":")) >= 3:
user = recu.split("!")[0]
user = user.split(":")[1]
for i in range(2, len(recu.split(":")), 1):
text = text + recu.split(":")[i] + ":"
print(user+" : "+text)
#Code here (like 'if' loops)
Thanks for help.
I found myself how to stop the issue : after the splitting lines, add elif "PING" in recu:
s.send("PONG :" + recu.split(":")[1]) the issue was that the bot don't respond to the ping from twitch, so twitch kicked him...

Python Socket - Multiple Clients

First as a disclaimer: I'm not the greatest at Python(or programming in general).
Having said that, I am having issues with Python Sockets. I am trying to build a simple chat client/server program, however, I am unable to have the server send the corresponding message(s) received from one client's socket, to the rest of the connected clients.
Here is the server code:
#!/usr/bin/python
import socket
import fnmatch
import thread
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
## Allow socket to be reused by application - doesn't force timeout.
serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
host = socket.gethostname()
port = 9000
serverSocket.bind((host,port))
connectedUsers = []
serverSocket.listen(5)
def threadedClient(clientStream):
while True:
clientMessage = clientStream.recv(1024).decode()
print clientMessage
if "Username:" in clientMessage:
username = clientMessage.replace("Username:","")
print str(username) + " has connected!"
connectedUsers.append(clientAddress)
print str(username) + "" + str(clientAddress) + " has connected to server"
for users in connectedUsers:
clientStream.sendto(str(username) + " has connected!", users)
if "Text:" in clientMessage:
receievedText = clientMessage.replace("Text:","")
for users in connectedUsers:
clientStream.sendto(receievedText.encode(), users)
print "Sending message " + str(receievedText) +" to:" + str(users)
if not clientMessage:
break
while True:
clientStream, clientAddress = serverSocket.accept()
thread.start_new_thread(threadedClient,(clientStream,))
Here is the client code:
#!/usr/bin/python
import socket
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 9000
username = raw_input("Please enter username: ")
clientSocket.connect((host, port))
clientSocket.send("Username:" + username)
def receiveServerMessage():
serverMessage = clientSocket.recv(1024).decode()
print serverMessage + '\n'
while True:
receiveServerMessage()
command = raw_input(username + " > ")
if command != None:
clientSocket.send("Text:" + str.encode(command))
if command == str("q"):
exit()
clientSocket.close()
The iteration seems to be awry when attempting to send the message to the other connected clients. I'm not sure if "sendto" is the proper way of handling this situation...especially since I believe it is UDP based. Any suggestions on how to handle socket stream correctly?
the problem is that the client is listening to the keyboard input before listening to the server socket , the best way to solve this is by using select() which similar to select() in c
here is a good example https://pymotw.com/2/select/

Using socket to get Minecraft bots join through a proxy (Python)

I need help with my minecraft bot client. I have gotten it working, but I have a problem with socket, it keeps throwing me error codes all the time. Here is the "critical" part of the code:
def connect(ip, port, username, indelay, joindelay):
global running
if not running:
return;
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = s.socksocket()
s.setproxy(socks.PROXY_TYPE_SOCKS5,"183.60.143.121, 1080")
s.connect((ip, port))
login = (chr(len(username)+2) + chr(0) + chr(len(username)) + username).encode("utf-8")
s.sendall(handshake)
s.sendall(login)
print("Pelaaja "+username+" liittyi")
time.sleep(indelay/2)
s.sendall(('\x02\x16' + chr(2)).encode('utf-8'))
try:
for x in spam:
if(len(x)==0): continue
s.sendall(chat(x))
except socket.error:
pass
time.sleep(indelay/2)
s.close()
print("Pelaaja "+username+" lopetti")
time.sleep(joindelay)
connect(ip, port, getRandomUsername(), indelay, joindelay)'

Python: Socket doesn't want to shutdown() and setsockopt() is ignored? (Problem debugging)

Edited
Original question was about trouble with reconnecting (close() and shutdown() confusion). The below code is the working code (fixed)
For Googler's, this script is an IRC bot. Feature list:
Keep reconnecting until connection available
If assigned nick is already taken, puts string behind name (repeats until success)
Listens to PING and responds with PONG
Can listen to commands and respond
If connection is lost, the bot will try to reconnect (if no information is received, no PING, in 5 mins, it treats the connection as if it was disconnected)
That is about it :)
Full Code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import socket
import string
import os
import platform
import time
# Variables
HOST = "irc.server.net"
PORT = 6667
NICK = "Nickname"
IDENT = "Nickname"
REALNAME = os.getenv('USER')
CHAN = "##Channel"
readbuffer = ""
# The Connection itself
keep_connecting = True
while keep_connecting:
irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
irc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
irc.settimeout(300)
try:
irc.connect((HOST, PORT))
pass
except socket.gaierror:
print "No connection, attempting to connect again"
time.sleep(5)
continue
print "Sending info..."
irc.send("NICK %s\r\n" % NICK)
irc.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME))
irc.send("JOIN :%s\r\n" % CHAN)
# Initial msg to send when bot connects
irc.send("PRIVMSG %s :%s\r\n" % (CHAN, "TehBot: "+ NICK + " Realname: " + REALNAME + " ."))
while True:
try:
data = irc.recv(4096)
print data
# If disconneted from IRC
if len(data) == 0:
print "Length of data == 0 ?..."
break
# If Nick is in use
if data.find (NICK + " :Nickname is already in use") != -1:
NICK = NICK + str(time.time())[5:-3]
break
# Ping Pong so we don't get disconnected
if data[0:4] == "PING":
irc.send ("PONG " + data.split() [ 1 ] + "\r\n")
except socket.timeout:
print "Socket timeout!"
irc.close()
break
This is most probably because you're switching off wi-fi and the interface is removed from system so you get something like Can't assign requested address. You would get such an error while trying to bind to non-existing local address.
The other thing is you won't be able to reconnect on the same socket after calling close as it releases all resources associated to the socket.

Categories

Resources