221 IRC Teams

Description

Tashi dele Rubyists,

This week’s quiz was suggested by Martin DeMello

A common feature in IRC-based games is the ability to create and join teams. The game bot sits in the channel and watches for messages in a certain format, which it interprets as commands. Write a small gamebot that accepts the following commands:

create team <teamname>
join <teamname>
leave team
show teams
show team <teamname>
show my team
delete team <teamname>
reset

Here’s a typical transcript

<foo> create team ruby
<bot> - created team ruby -
<bar> create team python
<bot> - created team python -
<foo> show teams
<bot> teams: ruby, python
<foo> show team ruby
<bot> team ruby: foo
<bar> show my team
<bot> bar is in team python
<baz> join ruby
<bot> baz is now in team ruby
<bar> show team ruby
<bot> team ruby: foo, baz

Think up some useful extensions, such as the ability to join a user rather than a team, and restricting some commands like reset to ops. There are plenty of IRC bot libraries out there, go explore! If one already does team formation, that’s cheating, though :)

Summary

This week’s quiz was solved by Martin DeMello.

Martin uses the rif gem to handle the nitty gritty details of IRC, like establishing a connection and sending and receiving messages.

The TeamBot#on_message method receives the messages from the users and dispatches them to an instance of the Teams class. This is accomplished by simply splitting the the message that was sent and using the first part as the method to invoke. The first argument is always the player, which is taken from the message event’s nick field. The rest of the message, if any, is passed as the remaining arguments.

Let’s look at a full pass through of the following sample message from user Bob:

<Bob> create ruby

This will land in the bot’s on_message method. The event will have “Bob” as the nick and “create ruby” as the message. That is parsed into the method to call and the arguments like so:

msg, *args = event.message.split(" ")

The teams object is then sent the parsed message arguments with the specified method as follows:

*ret = teams.send(msg, player, *args)

This takes us into the create method and the team is created (if all goes according to plan):

def create(player, team)
  raise TeambotError("team #{team} already created") if teams[team]
  teams[team] = true
  "created team #{team}"
end

The other actions that users may wish to perform are taken care of in the same way. This simple and flexible solution allows for easy modification and extension.

Thank you Martin for your solution (and also for the quiz suggestion)!

IRC Teams (#221) - Solutions


Sunday, October 11, 2009