IRC bot won't connect to server - Python - python

I don't know what I'm doing wrong. There are no errors or anything, It just keeps saying I'm not registered. This is also an IRC channel and network that does not require registering nicks to use. Thanks in advance.
#I've set variables and imported stuff up here
socket.connect((host, port))
socket.recv(512)
socket.send('NICK %s' % (username))
socket.send('USER %s %s %s :%s\r\n' % (username, username, username, username))
pingPong = socket.recv(512)
print pingPong
pingPong = pingPong[5:]
print 'PONG ' + pingPong
socket.send('PONG %s\r\n' % pingPong)
print 'PONG ' + host + '\r\n'
time.sleep(5) #I even added this time.sleep() to wait for the PONG to go through.
socket.send('JOIN %s\r\n' % channel)
socket.recv(1024)
#I have a while loop that continually receives data and commands down here
This outputs:
PING :912E235B
PONG :912E235B
:irc.va.us.mibbit.net 451 JOIN :You have not registered

Your NICK and USER commands are malformed. NICK should have an "\r\n" at the end. USER should not just be your username 4 times. Below is a working connection to that irc server.
import socket
host = "irc.va.us.mibbit.net"
port = 6667
username = "andrew"
channel = "luck"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
print "recv 1", s.recv(512)
s.send('NICK %s\r\n' % (username,))
s.send('USER %s 8 * :%s\r\n' % (username, username))
pingPong = s.recv(512)
print "recv 2", pingPong
pingPong = pingPong[5:]
s.send('PONG %s\r\n' % pingPong)
s.send('JOIN %s\r\n' % (channel,))
msg = s.recv(1024)
print "Message", msg

Related

Python Bluetooth: how to send a file from windows to Raspberry Pi

I need to transfer a file from my Windows laptop to a Raspberry Pi, and also measure the speed and transfer time of the file. Looking on the internet I chose to use Pybluez, but I am sure there is something missing to realise the transfer to a Raspberry Pi and I don't understand what. I should probably figure out how to merge the pieces of code.This is the inquiry code:
import bluetooth
print("performing inquiry...")
nearby_devices = bluetooth.discover_devices(
duration=8, lookup_names=True, flush_cache=True, lookup_class=False)
print("found %d devices" % len(nearby_devices))
for addr, name in nearby_devices:
try:
print(" %s - %s" % (addr, name))
except UnicodeEncodeError:
print(" %s - %s" % (addr, name.encode('utf-8', 'replace')))
This is the code for the server (i.e. the device that has to send the file, in my case it's my laptop, right?):
from bluetooth import *
server_sock=BluetoothSocket( RFCOMM )
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)
port = server_sock.getsockname()[1]
uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"
advertise_service( server_sock, "SampleServer",
service_id = uuid,
service_classes = [ uuid, SERIAL_PORT_CLASS ],
profiles = [ SERIAL_PORT_PROFILE ],
# protocols = [ OBEX_UUID ]
)
print("Waiting for connection on RFCOMM channel %d" % port)
client_sock, client_info = server_sock.accept()
print("Accepted connection from ", client_info)
try:
while True:
data = client_sock.recv(1024)
if len(data) == 0: break
print("received [%s]" % data)
except IOError:
pass
print("disconnected")
client_sock.close()
server_sock.close()
print("all done")
This is the code for the client (which in my case would then be the Raspberry Pi):
from bluetooth import *
import sys
if sys.version < '3':
input = raw_input
addr = None
if len(sys.argv) < 2:
print("no device specified. Searching all nearby bluetooth devices for")
print("the SampleServer service")
else:
addr = sys.argv[1]
print("Searching for SampleServer on %s" % addr)
# search for the SampleServer service
uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"
service_matches = find_service( uuid = uuid, address = addr )
if len(service_matches) == 0:
print("couldn't find the SampleServer service =(")
sys.exit(0)
first_match = service_matches[0]
port = first_match["port"]
name = first_match["name"]
host = first_match["host"]
print("connecting to \"%s\" on %s" % (name, host))
# Create the client socket
sock=BluetoothSocket( RFCOMM )
sock.connect((host, port))
print("connected. type stuff")
while True:
data = input()
if len(data) == 0: break
sock.send(data)
sock.close()
What should i do? does the client-server code work directly by running the client programme on the Raspberry and the server on the computer? How can i then transfer the file? Is this a correct method or not?
Help me please!

UDP server can't send packet to the client

I have two computer(A and B) in the different VLAN.
the IP of the computer A server is x.x.180.70 and IP of the computer B is x.x.181.52.
the computer A bind 19999 port as the UDP server and B as the client.
A can recv the packet from B, but B can't recv the packet from A.
so i capture the packet with wireshark, the results shown that the server reply packet with another port. In common the server reply packet with the bound port. Why does the server use the different port?
Then I wrote a TCP Server on computer A, it works well.
The udp server works if A and B at the same vlan. Is there any body have idea? thanks!
Code(Python):
#!/usr/bin/python3
#coding=utf-8
import socket
import sys
def server(addr):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(addr)
print("server started, listen on %s" % str(addr))
while True:
print("wait msg....")
data, cconn = sock.recvfrom(1024)
client_addr = "%s:%d" % (cconn[0], cconn[1])
resp = "hello client"
print("recv msg from %s <- %s" % (client_addr, data.decode('utf-8')))
sock.sendto(resp.encode("utf-8"), cconn)
print("send msg to %s -> %s" % (client_addr, resp))
def client(addr):
server_addr = "%s:%d" % (addr[0], addr[1])
print("send msg to %s" % server_addr)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.connect(addr)
sock.sendto("hello server".encode("utf-8"), addr)
data, conn = sock.recvfrom(1024)
resp = data.decode("utf-8")
print("recv msg from %s <- %s" % (server_addr, resp))
def usage():
print("Usage:")
print(" python3 udp.py server [ip:port]")
print(" python3 udp.py client [ip:port]")
if __name__ == "__main__":
if len(sys.argv) < 3:
usage()
exit(0)
role = sys.argv[1]
array = sys.argv[2].split(":")
address = (array[0], int(array[1]))
if role == "server":
server(address)
elif role == "client":
client(address)
else:
usage()

Socket python can't send information to the server "client.send(name)"

I'm working on a game project with tkinter and Python 3.7 and i can't send the name of the player that i'm typing to the server.
Server
server = None
HOST_ADDR = "192.168.1.13"
HOST_PORT = 5555
client_name = ""
clients = []
clients_names = []
player_data = []
def start_server():
global server, HOST_ADDR, HOST_PORT # code is fine without this
btnStart.config(state=tk.DISABLED)
btnStop.config(state=tk.NORMAL)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("socket.AF_INET")
print("socket.SOCK_STREAM")
server.bind((HOST_ADDR, HOST_PORT))
server.listen(5) # server is listening for client connection
threading._start_new_thread(accept_clients, (server, " "))
lblHost["text"] = "Address: " + HOST_ADDR
lblPort["text"] = "Port: " + str(HOST_PORT)
def accept_clients(the_server, y):
while True:
if len(clients) < 2:
client, addr = the_server.accept()
clients.append(client)
# use a thread so as not to clog the gui thread
threading._start_new_thread(send_receive_client_message, (client, addr))
Client.py
client = None
HOST_ADDR = "192.168.1.13"
HOST_PORT = 5555
def connect():
global your_details
if len(ent_name.get()) < 1:
tk.messagebox.showerror(title="ERROR!!!", message="You MUST enter your first name <e.g. John>")
else:
your_details["name"] = ent_name.get()
connect_to_server(ent_name.get())
def connect_to_server(name):
global client, HOST_PORT, HOST_ADDR
try:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST_ADDR, HOST_PORT))
print('test') # OK, i can receive the print
client.send(name)
print('test') # can't receive the print
threading._start_new_thread(receive_message_from_server, (client, "m"))
top_welcome_frame.pack_forget()
top_frame.pack(side=tk.TOP)
window_main.title("Tic-Tac-Toe Client - " + name)
except Exception as e:
tk.messagebox.showerror(title="ERROR!!!", message="Cannot connect to host: " + HOST_ADDR + " on port: " + str(
HOST_PORT) + " Server may be Unavailable. Try again later")
Each time i enter a name, it doesn't send the name that i typed client.send(name) and it goes in the else.
If someone can help me with that.
Thank you for your help !

How to send stream trough socket when using select()?

After long hours of research and testing I finally ask here.
My script has to handle multiple client connections and in the same time has to get and send a stream from another socket.
Finally I've been able to make it work but only for one user. That user connects to the socket, the script connects to the other socket, then return the stream to the client.
The script works pretty well but has a some hard limitations :
- it send the stream to the client but,
- even if the socket is in non-blocking mode I think that calling a socket inside another one is the main reason why it reacts like it was in blocking mode (because one ot these is continuously sending datas ?)
By the way I think that the select() method could allow me to do what I want, but I don't clearly understand how.
Here is the server code taht works for one client, but is blocking
#!/usr/bin/env python
# coding: utf-8
from __future__ import print_function
import sys, time, base64, socket
server_ip = 'XX.XX.XX.XX'
def caster_connect(connected_client, address):
username = 'XXXXXXX'
password = 'XXXXXXXXX'
host = 'XX.XX.XX.XX'
port = 2102
pwd = base64.b64encode("{}:{}".format(username, password).encode('ascii'))
pwd = pwd.decode('ascii')
u_message = ''
stream_type = 'CMRp'
header = \
"GET /" + str(stream_type) + " HTTP/1.1\r\n" +\
"Host " + str(host) + "\r\n" +\
"Ntrip-Version: Ntrip/1.0\r\n" +\
"User-Agent: my_script.py/0.1\r\n" +\
"Accept: */*\r\n" +\
"Authorization: Basic {}\r\n\r\n".format(pwd) +\
"Connection: close\r\n"
print("Connecting to caster...\n")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,int(port)))
s.send(header.encode('ascii'))
print("Waiting answer from caster...\n")
while True:
try:
data = s.recv(2048)
connected_client.send(data)
print("Sending data from caster at %s" % time.time())
sys.stdout.flush()
# On any error, close sockets
except socket.error, e:
print("No data received from caster : %s" % e)
print("Close client connection at %s" % format(address))
s.close()
break
return
#----------------
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((server_ip, 5680))
sock.settimeout(3)
try:
while True:
try:
sock.listen(5)
client, address = sock.accept()
print ("%s connected" % format(address) )
msg = client.recv(4096)
except socket.timeout, e:
err = e.args[0]
if err == 'timed out':
print("Timed out, retry later")
continue
else:
print(socket.error)
sock.close()
except socket.error:
print(socket.error)
sock.close()
else:
if len(msg) == 0:
print("Shutdown on client end")
sock.close()
else:
print(msg)
caster_response = caster_connect(client, address)
sys.stdout.flush()
print("Close")
client.close()
sock.close()`enter code here`
except KeyboardInterrupt:
print("W: Keyboard interrupt, closing socket")
finally:
sock.close()
And this is the code I found to handle select()
#!/usr/bin/env python
# coding: utf-8
import select, socket, sys, Queue
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setblocking(0)
server.bind(('XX.XX.XX.XX', 64000))
server.listen(5)
inputs = [server]
outputs = []
message_queues = {}
while inputs:
readable, writable, exceptional = select.select(
inputs, outputs, inputs)
for s in readable:
if s is server:
connection, client_address = s.accept()
print("New connection from %s" % client_address)
connection.setblocking(0)
inputs.append(connection)
message_queues[connection] = Queue.Queue()
else:
data = s.recv(1024)
print("Data received : %s" % data)
if data:
message_queues[s].put(data)
if s not in outputs:
outputs.append(s)
else:
if s in outputs:
outputs.remove(s)
inputs.remove(s)
s.close()
del message_queues[s]
for s in writable:
try:
next_msg = message_queues[s].get_nowait()
print("Next msg : %s" % next_msg)
except Queue.Empty:
outputs.remove(s)
else:
s.send(next_msg)
for s in exceptional:
inputs.remove(s)
if s in outputs:
outputs.remove(s)
s.close()
del message_queues[s]
In this code (found at this page) I didn't make changes as I don't know how to handle this.
Maybe by creating another server script that would only handle the stream part, so the main script would act as a server for clients, but as client for the stream part ?

Making a module use functions and variables defined within the main program

I'm making an IRC bot for my network. To make the code cleaner, I am defining functions in modules. All these modules are in a folder called "plugins". One module say calls the function sendMsg and fails because it's trying to run a function defined in the main program. I also want to have this module to be able to access variables defined in the main program after the program has started.
import socket
import time
import re
from plugins.say import *
host = "irc.somenetwork.net"
port = 6667
nick = "ircbot"
channels = "##bottesting"
s = socket.socket()
def connect():
s.connect((host, port))
s.send("NICK %s\r\n" % nick)
s.send("USER %s %s nul :%s\r\n" % (nick, nick, nick))
time.sleep(3)
s.send("JOIN %s\r\n" % channels)
time.sleep(3)
def sendMsg(chan, msgSend):
s.send("PRIVMSG %s :%s\r\n" % (chan,msgSend))
# print "Sending message \"%s\" to channel/user \"%s\"" % (msgSend, chan)
def quitServ(quitMsg="m8bot"):
s.send("QUIT %s\r\n" % quitMsg)
connect()
while 1:
msgRaw = s.recv(1024)
print msgRaw
if msgRaw == "":
break
if "PING" in msgRaw:
print "Pong!"
PONG = msgRaw.split(' ')
PONG[0] = PONG[0].replace('PING','PONG')
PONG = ' '.join(PONG)
s.send("%s\r\n" % PONG)
if "PRIVMSG" in msgRaw:
# print "PRIVMSG detected"
user = ''.join(re.compile("(?<=:).{0,}(?=.{0,}!)").findall(msgRaw.split(' ')[0]))
channel = msgRaw.split(' ')[2]
command = (' '.join(msgRaw.split(' ')[3:]).replace(":","",1)).split(' ')[0]
msg = ''.join((' '.join(msgRaw.split(' ')[3:]).replace(":","",1)).split(' ')[1:]).replace("\r\n","")
if not "#" in channel:
channel = user
print "Nick: %s\nChannel: %s\nCommand: %s\nMsg: %s" % (user,channel,command,msg)
if ".quit" in command:
if msg:
quitServ(str(msg))
else:
quitServ()
if ".hello" in command:
# print "Attempting to send Hello World message."
sendMsg(channel, "Hello World!")
if ".say" in command:
say(msg)
quitServ()
This is my program. function say() is as follows:
def say(msg):
sendMsg(channel, "You said: %s" % msg)
I can see what the problem is, but I don't know how I would fix this. Feedback appreciated :)
-Nia
Try import __main__ in your say.py.
And then your say function should look something like this:
def say():
__main__.sendMsg(channel, "You said: %s" % msg)
But this is not a best solution. Just solution with less code changes.

Categories