2010-09-14 10:11:05 +00:00
The first thing you need to do is import the sockets module<br>
<code>import sockets</code><br>
Then you need to create and initialize a TSocket object<br>
2010-09-14 10:11:07 +00:00
<code>var s: TSocket = socket()</code><br>
2010-09-14 10:11:05 +00:00
After that you can use <code>s.connect("addr", TPort(80))</code> to connect to a server<br>
Once you connect to a server, you can send and receive messages to/from the server by using <code>s.send("Message")</code> to send, and <code>s.recv()</code> to receive.
2010-09-14 10:11:07 +00:00
2010-09-14 10:11:08 +00:00
<pre>
2010-09-14 10:11:06 +00:00
import sockets, strutils
2010-09-14 10:11:05 +00:00
when not defined(strutils.toStringSep):
proc toStringSep(x: int64): string =
var s = $x
result = ""
var j = 0
for i in countdown(len(s)-1, 0):
inc(j)
if j == 4:
result = ',' & result
j = 0
result = s[i] & result
proc toMiB(size: int64): int64 =
return size div 1024 div 1024
proc formatSize(size: int64): string =
var gigabytes: int64 = size div 1024 div 1024 div 1024
var megabytes: int64 = size.toMiB()
var kilobytes: int64 = size div 1024
if gigabytes != 0:
return toStringSep(gigabytes) & "GB"
elif megabytes != 0:
return toStringSep(megabytes) & "MB"
elif kilobytes != 0:
return toStringSep(kilobytes) & "KB"
else:
return toStringSep(size) & "B"
var s = socket()
s.connect("irc.freenode.net", TPort(6667))
s.send("NICK NimrodBot\c\L")
s.send("USER NimrodBot * 0 :IRC Bot programmed in Nimrod!\c\L")
while True:
var data: string = ""
discard s.recvLine(data)
echo(data)
if data.split()[0] == "PING":
s.send("PONG " & data.split()[1] & "\c\L")
if data.split()[1] == "001":
s.send("JOIN #nimrod\c\L")
if data.split()[1] == "PRIVMSG":
if data.split()[3] == ":!about":
2010-09-14 10:11:06 +00:00
var msg = "NimrodBot 0.1 compiled on " & CompileDate & " " & CompileTime
msg.add(" running on " & hostOS)
2010-09-14 10:11:05 +00:00
s.send("PRIVMSG " & data.split()[2] & " :" & msg & "\c\L")
elif data.split()[3] == ":!mem":
2010-09-14 10:11:06 +00:00
var msg = "Occupied memory: " & formatSize(int64(getOccupiedMem()))
2010-09-14 10:11:05 +00:00
s.send("PRIVMSG " & data.split()[2] & " :" & msg & "\c\L")
elif data.split()[3] == ":!freemem":
2010-09-14 10:11:06 +00:00
var msg = "Free memory: " & formatSize(int64(getFreeMem()))
2010-09-14 10:11:05 +00:00
s.send("PRIVMSG " & data.split()[2] & " :" & msg & "\c\L")
elif data.split()[3] == ":!totalmem":
2010-09-14 10:11:06 +00:00
var msg = "Total memory: " & formatSize(int64(getTotalMem()))
s.send("PRIVMSG " & data.split()[2] & " :" & msg & "\c\L")
2010-09-14 10:11:08 +00:00
</pre>