gobot

package module
v0.0.0-...-c38097a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 25, 2015 License: MIT Imports: 17 Imported by: 1

README

THIS PROJECT IS NO LONGER MAINTAINED AS OF 18/8/2015. FORK AT YOUR OWN RISK.

Pokémon Showdown! GoBot

Another Pokémon Showdown! bot, this time in Go. Written by TalkTakesTime as a learning exercise.

Installation

This bot runs on Go, Google's open-source language, and was developed for version 1.4.2, although it has not been tested on any other versions.

It requires the following packages to run:

  • encoding/json -- for logging in
  • errors -- for custom errors
  • flag -- for command line arguments
  • github.com/TalkTakesTime/hookserve -- for GitHub webhooks
  • github.com/tonnerre/golang-pretty -- for pretty printing
  • golang.org/x/net/websocket -- for websockets
  • gopkg.in/yaml.v2 -- for parsing the config
  • io/ioutil -- for reading files and http responses
  • log -- for logging
  • net/http -- for logging in
  • net/url -- for logging in
  • os -- for dealing with log files
  • regexp -- for the PS standard toId function
  • strconv -- for converting between int and string
  • strings -- for message parsing
  • time -- for sleeping etc

I will assume that you know how to clone a Git repository or otherwise obtain the source code (hint: go get github.com/TalkTakesTime/gobot works). To install the dependencies, navigate to the directory you downloaded this repository to, and run

go get .
go build

To build and start the bot, run

cd main
go build
./main

If you want to give the executable a custom name, use

go build -o name

and if you would like it to log to a file filename.log rather than to stdout, use

./main -log=filename.log

To log to a file whose name is the current date, use

./main -log=$(date -Iseconds).log

From there, you're on your own! However, one final warning: the bot will panic if the port chosen for config.HookPort is already in use, so choose carefully.

License

GoBot is distributed under the terms of the MIT License.

Documentation

Index

Constants

View Source
const (
	GitIOBase   = "http://git.io/"
	GitIOCreate = "http://git.io/create"

	// template for push messages
	// [repo] user pushed number new commits? to branch: URL
	PushTemplate = "[%s] %s pushed %s new commit%s to %s: %s"
	// template for commit messages
	// repo/branch SHA user: commit message
	CommitTemplate = "%s/%s %s %s: %s"
	// template for pull request messages
	// [repo] user action pull request #number: message (upstream...base) URL
	PullReqTemplate = "[%s] %s %s pull request #%s: %s (%s...%s) %s"
)
View Source
const (
	BufferSize = 4096
)
View Source
const (
	GitHubBaseURL = "https://github.com/"
)

Variables

View Source
var (
	LoginUrl = "https://play.pokemonshowdown.com/action.php"
	IdRegex  = regexp.MustCompile("[^a-z0-9]+")
)
View Source
var (
	GitSHARegex  = regexp.MustCompile("^[a-f0-9]{7,40}$")
	GitLineRegex = regexp.MustCompile("(#L?)?([0-9]+)")
)
View Source
var (
	ErrShortenURL = errors.New("could not shorten the URL")
)
View Source
var PingTicker *time.Ticker

Functions

func FormatBranch

func FormatBranch(branch string) string

FormatBranch formats a branch for !htmlbox using #9C009C.

func FormatName

func FormatName(name string) string

FormatName formats a name for !htmlbox using #7F7F7F. Note that it uses a different colour to the IRC version due to PS' background colour.

func FormatRepo

func FormatRepo(repo string) string

FormatRepo formats a repo name for !htmlbox using #FF00FF.

func FormatSHA

func FormatSHA(sha string) string

FormatSHA formats a commit SHA for !htmlbox using #7F7F7F.

func FormatSize

func FormatSize(size int) string

FormatSize formats an event size for !htmlbox using <strong>.

func FormatURL

func FormatURL(url string) string

FormatURL formats a URL for !htmlbox.

func ShortenURL

func ShortenURL(longURL string) (string, error)

Utility to shorten a URL using http://git.io/ Returns an empty string and ErrShortenURL if something goes wrong, otherwise returns the shortened URL and nil

Types

type Bot

type Bot struct {
	// contains filtered or unexported fields
}

func CreateBot

func CreateBot(conf Config) Bot

Creates and returns a bot using the given configuration, loading the commands in commands.go

func (*Bot) CreateHook

func (bot *Bot) CreateHook()

Generates the GitHub webhook receiver and starts a goroutine to deal with received events

func (*Bot) GetCommand

func (bot *Bot) GetCommand(msg string) string

Gets the command name from a message, if there is one. If not, returns the empty string.

func (*Bot) HandlePullHook

func (bot *Bot) HandlePullHook(event hookserve.Event)

Sends messages to all relevant rooms updating them when a pull_request event is received. Still in beta

func (*Bot) HandlePushHook

func (bot *Bot) HandlePushHook(event hookserve.Event)

Sends messages to all relevant rooms updating them when a push event is received. Tells how many commits were pushed, and gives a description of each individual commit, as given in the commit message

func (*Bot) JoinRoom

func (bot *Bot) JoinRoom(room string)

Causes the bot to join the given room and record when it joined in bot.config.Rooms

func (*Bot) ListenForHooks

func (bot *Bot) ListenForHooks()

Listens for GitHub webhook events and delegates them to handlers, such as `HandlePushHook`. Currently only push and pull_request events are supported

func (*Bot) LoadCommands

func (bot *Bot) LoadCommands()

Loads the commands that are specified within the function. A command can then be called using `bot.commands["name"](msg)`.

Messages will have arguments of the following form:

{user, args, command name[, timestamp]}

func (*Bot) LogIn

func (bot *Bot) LogIn(challstr Message)

Log in to PS! under the given name and password. See PS! documentation if you want to understand exactly what is required for login.

func (*Bot) MainLoop

func (bot *Bot) MainLoop()

Begins the main loop of the bot, which keeps it running indefinitely (or until it crashes, since I haven't given it any form of crash handling yet.)

func (*Bot) ParseMessage

func (bot *Bot) ParseMessage(msg Message)

Parses a non-raw message and determines what action to take in reponse. Currently most messages are ignored.

func (*Bot) ParseRawMessage

func (bot *Bot) ParseRawMessage(rawMsg string) []Message

Takes a single raw message from PS! and breaks it up into individual messages to respond to, returning a slice of Messages to be dealt with by the main parser.

func (*Bot) QueueMessage

func (bot *Bot) QueueMessage(text, room string)

Adds a message for the given room to the outgoing queue. If the message is a PM, the room should be of the form "user:name", and the message will automatically get sent as a PM, so there is no need to add "/pm user, " to the front.

func (*Bot) Receive

func (bot *Bot) Receive()

Receives messages from PS and queues them up to be handled. Use as a goroutine or otherwise it will loop infinitely.

func (*Bot) RunCommand

func (bot *Bot) RunCommand(msg Message)

Checks if the given command exists and executes the function it refers to if it does. Otherwise ignores the command.

func (*Bot) Send

func (bot *Bot) Send()

Reads messages from the out queue and sends them to PS, one each 0.5s or so to avoid the chat queue at the PS end filling up and blocking more messages

func (*Bot) SendMessage

func (bot *Bot) SendMessage(msg string)

Sends a queued message through the websocket connection

func (*Bot) Start

func (bot *Bot) Start()

Connects to PS! and begins the bot running.

type Config

type Config struct {
	/**** General config ****/
	// The nickname to use on PS!. Limited to 16 characters
	Nick string
	// The password associated with the given nick. Blank if
	// the nick is unregistered
	Pass string
	// The server to connect to. PS! main's server is sim.smogon.com
	Server string
	// The port the given server uses. Default should be 8000
	Port string
	// The websocket URL to connect to. Generate automatically from
	// the given settings using Config.GenerateURL
	URL *url.URL
	// The character that indicates that the message received is for the bot
	// to respond to. TODO: add validation for command char
	CommandChar string
	// The rooms the bot is in. Initially loaded from the config file, and
	// updated whenever the bot joins a room.
	Rooms map[string]int64

	/**** Git config ****/
	// Whether or not the bot should listen for webhooks
	EnableHooks bool
	// The port that the bot should listen on for incoming GitHub webhooks
	HookPort int
	// The secret given during the creation of the webhook. Must match the
	// secret on GitHub
	HookSecret string
	// A list of rooms to update when a webhook is received
	HookRooms []string
	// Aliases for .git, of the form alias: user/repo
	GitAliases map[string]string
}

func GetConfig

func GetConfig() Config

Reads the bot's config from file and converts it to a Config object for use by a Bot.

func (*Config) GenerateURL

func (conf *Config) GenerateURL()

Generates a websocket URL to use for connecting, based on the given parameters. The websocket URL has the following format:

ws://server:port/showdown/websocket

type Message

type Message struct {
	// contains filtered or unexported fields
}

A Message struct is a simpler way of dealing with the message data from the messages PS! sends, as it contains all the information that is needed in a much easier to access form than a raw message from PS!. They can be created by passing a raw message into `NewMessage`, along with the room the message was received in.

func NewMessage

func NewMessage(room, raw string) Message

Creates a Message object for the given message with all required information for parsing it and responding later.

func (*Message) GetArgs

func (msg *Message) GetArgs()

Determines the type of the message and its contents from its raw data. Certain messages get parts of them discarded as we're not interested in those parts (e.g., the timestamp in a |c:| message).

type ShortURLError

type ShortURLError struct {
	URL string // the URL trying to be shortened
	Err error
}

Error encountered when a URL can't be shortened using a URL shortener such as git.io or goo.gl

func (*ShortURLError) Error

func (e *ShortURLError) Error() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL