473,402 Members | 2,064 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,402 software developers and data experts.

IRC bot problem

Thekid
145 100+
How can I go about writing a simple IRC bot? I read one thread in this forum about an IRC bot but I couldn't get it to work. I've looked at a few like eggdrop, supybot and phenny but I want to try a very simple basic one so I can understand the code a little better. Where should I start?
Jul 23 '07 #1
7 3456
Thekid
145 100+
import sys
import socket
import string
import os

HOST='irc.freenode.net'
PORT=6667
NICK='Thekid'
IDENT='IRCbot'
REALNAME='TheDuke'
OWNER='Me'

s=socket.socket( )
s.connect((HOST, PORT))
s.send('NICK '+NICK+'n')
s.send('USER '+IDENT+' '+HOST+' bla :'+REALNAME+'n')
Jul 24 '07 #2
Thekid
145 100+
Why won't something like this work to simply connect to a site and join?

Expand|Select|Wrap|Line Numbers
  1. import irclib
  2.  
  3. # Connection information
  4. network = 'irc.blahblah.net'
  5. port = 6667
  6. channel = '#blah'
  7. nick = 'blah'
  8. name = 'blah'
  9.  
  10. # Create an IRC object
  11. irc = irclib.IRC()
  12.  
  13. # Create a server object, connect and join the channel
  14. server = irc.server()
  15. server.connect ( network, port, nick, ircname = name )
  16. server.join ( channel )
  17.  
  18. # Jump into an infinite loop
  19. irc.process_once()
  20.  
Jul 24 '07 #3
Thekid
145 100+
Why won't something like this work to simply connect to a site and join?

Expand|Select|Wrap|Line Numbers
  1. import irclib
  2.  
  3. # Connection information
  4. network = 'irc.blahblah.net'
  5. port = 6667
  6. channel = '#blah'
  7. nick = 'blah'
  8. name = 'blah'
  9.  
  10. # Create an IRC object
  11. irc = irclib.IRC()
  12.  
  13. # Create a server object, connect and join the channel
  14. server = irc.server()
  15. server.connect ( network, port, nick, ircname = name )
  16. server.join ( channel )
  17.  
  18. # Jump into an infinite loop
  19. irc.process_once()
  20.  
Line 19 should read irc.process_forever() instead of _once
Jul 24 '07 #4
That code looks exactly like mine, and I've had mine working for over a onth using irclib. Try setting 'debug' to 1 in the irclib module.
Jul 25 '07 #5
Thekid
145 100+
Thanks for the reply. I've gone in another direction with it and can now connect and have the bot repy to some basic comments but I still have things that need worked out.
Aug 2 '07 #6
Thekid
145 100+
When my bot joins a room it will respond to certain words that are typed. An example would be that if someone typed "hello" the bot would reply "Hello <user>! How are you doing?" My problem is that I can't seem to get the bot to reply to NOTICE or PRIVMSG from a user. I'm not sure what I'm overlooking. I can get the bot to reply with a NOTICE or PRIVMSG to a user but only if the received message is from the channel and NOT a NOTICE or PRIVMSG from a user. example: channel = #bottest
User types "hello"
(I get "Received message from <userinfo> NOTICE #bottest:hello
bot replies NOTICE user "Hello <user>! How are you doing?"
How can I get the bot to respond to a NOTICE from a user instead of a NOTICE from the channel?

I've tried changing the def main() portion to def messageFromUser but that didn't do it. Now before,
I had self.sendmessageToChannel(channel, "blah blah") but had to change 'channel' to 'user' because it would send the reply by NOTICE or PRIVMSG to everyone in the channel instead of to just the user.
I hope I'm making sense.... http://python-forum.org/py/images/sm...n_confused.gif

I've included the portions of code that I think the problem is in, it's not the complete code:

Expand|Select|Wrap|Line Numbers
  1.  
  2. #debug set to 'True' so I can read the output
  3. #starts with the usual of host, port, nick, etc.....
  4. #then the ping & pong........
  5.  
  6. # Callbacks you may implement instead of delving into the raw data passed to  IRCBot.act
  7.     def messageFromChannel(self, channel, user, message):
  8.         """ Callback called when a message is received from a channel the bot is residing 
  9. in."""
  10.         dbg("Received message from '" + str(user) + "' in channel '" + "':\n" + message)
  11.  
  12.     def sendMessageToChannel(self, channel, message):
  13.         """ Sends a message to a channel. """
  14.         self.send("NOTICE " + channel + " :" + message)
  15.  
  16.     def messageFromUser(self, user, message, msgtype=None):
  17.         """ Callback called when a message is received from a user."""
  18.         dbg("Received message from '" + user + "':\n" + message)
  19.  
  20.     def sendMessageToUser(self, user, message):
  21.         """ Sends a message to a user. """
  22.         self.send("NOTICE " + user + " :" + message)
  23.  
  24.  
  25.     def userEntered(self, user, channel):
  26.         #""" Callback called when a new user enters a channel you are in. """
  27.         dbg(user + " entered channel " + channel)
  28.     def act(self, data):
  29.         """ Callback which is passed raw data from the IRC server received from the 
  30. socket."""
  31.         pass
  32.  
  33.     def reply(self, data, message):
  34.         """ Sends a message to either a channel or an individual, based on the text 
  35. passed."""
  36.         # call getChannel passing True as the username param.
  37.         self.sendMessageToChannel(self.getChannel(data), message, True)    
  38.  
  39.     def getSenderName(self, data):
  40.         """ Get the name of the person who sent a message, given the raw IRC message."""
  41.         try:
  42.             regSenderName = re.compile(":[\w\s]*")
  43.             return re.sub("^:", "", regSenderName.findall(data)[0])
  44.         except IndexError:
  45.             return None
  46.  
  47.     def getChannel(self, data, username=True):
  48.         """ Gets the channel a message was sent from."""
  49.         # make self.reply handle the checking of user/channel.
  50.         if not data.count("#") and username:
  51.             return self.getSenderName(data)
  52.         else:
  53.             try:
  54.                 channel = data[data.index("#"):]
  55.                 return channel[:channel.index(" ")]
  56.             except ValueError:
  57.                 return None
  58.  
  59.     def recv(self, amount):
  60.         """ Receives text from the IRC server."""
  61.         return self.sock.recv(amount)
  62.  
  63.     def send(self, text):
  64.         """ Send a raw IRC command to the server."""
  65.         self.sock.send(text + "\n\r")
  66.         dbg("bot -> " + text)
  67.  
  68.     # <code removed for sake of space......connection code
  69.  
  70. def baseAct(self, data):
  71.         """ Parses the received data and responds accordingly. It parses the data and calls
  72.             the necessary callbacks."""
  73.         # Call the callbacks.
  74.         channel = self.getChannel(data, False)
  75.         sender = self.getSenderName(data)
  76.         # messageFromChannel
  77.         if channel:
  78.             # Get senders name when message received from channel
  79.             if not sender:
  80.                 sender = None
  81.             self.messageFromChannel(channel, sender, data[data.find(" :") + 2:])
  82.         # userEntered
  83.         elif sender and data[data.find(" ") + 1:].startswith("JOIN :"):
  84.             self.userEntered(sender, data[data.find("JOIN :") + 6:])
  85.         elif sender:
  86.             # Make sure this is a message (NOTICE or PRIVMSG).
  87.             ok = False
  88.             if data[data.find(" ") + 1:].startswith("NOTICE %s :" % self.nick):
  89.                 ok = True
  90.             elif data[data.find(" ") + 1:].startswith("PRIVMSG %s :" % self.nick):
  91.                 ok = True
  92.             # messageFromUser
  93.             if ok:
  94.                 self.messageFromUser(sender, data[data.find(":") + 2:])
  95.             # Pass the data to self.act
  96.         self.act(data)
  97.  
  98. def main():
  99.     """ Called when this module is ran directly. """
  100.     class MrXbot(IRCBot):
  101.         def messageFromChannel(self, channel, user, message):
  102.             if message.startswith("hello"):
  103.                 self.sendMessageToChannel(user, "Hello %s! How are you doing?" % user)
  104.             elif message.startswith("wtf"):
  105.                 self.sendMessageToChannel(user, "That's not very nice behavior " + user )
  106.  
  107.              # < I have a longer list of replies and comments but you get the idea......
  108.  
  109. bot.close()
  110.  
  111.  
Aug 8 '07 #7
Thekid
145 100+
Nevermind, I simplified the code and figured it out.
Aug 15 '07 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

11
by: Kostatus | last post by:
I have a virtual function in a base class, which is then overwritten by a function of the same name in a publically derived class. When I call the function using a pointer to the derived class...
117
by: Peter Olcott | last post by:
www.halting-problem.com
18
by: Ian Stanley | last post by:
Hi, Continuing my strcat segmentation fault posting- I have a problem which occurs when appending two sting literals using strcat. I have tried to fix it by writing my own function that does the...
28
by: Jon Davis | last post by:
If I have a class with a virtual method, and a child class that overrides the virtual method, and then I create an instance of the child class AS A base class... BaseClass bc = new ChildClass();...
6
by: Ammar | last post by:
Dear All, I'm facing a small problem. I have a portal web site, that contains articles, for each article, the end user can send a comment about the article. The problem is: I the comment length...
16
by: Dany | last post by:
Our web service was working fine until we installed .net Framework 1.1 service pack 1. Uninstalling SP1 is not an option because our largest customer says service packs marked as "critical" by...
2
by: Mike Collins | last post by:
I cannot get the correct drop down list value from a drop down I have on my web form. I get the initial value that was loaded in the list. It was asked by someone else what the autopostback was...
0
by: =?Utf-8?B?am8uZWw=?= | last post by:
Hello All, I am developing an Input Methop (IM) for PocketPC / Windows Mobile (PPC/WM). On some devices the IM will not start. The IM appears in the IM-List but when it is selected from the...
1
by: sherifbk | last post by:
Problem description ============== - I have 4 clients and 1 server (SQL server) - 3 clients are Monitoring console 1 client is operation console - Monitoring console collects some data from...
9
by: AceKnocks | last post by:
I am working on a framework design problem in which I have to design a C++ based framework capable of solving three puzzles for now but actually it should work with a general puzzle of any kind and I...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.