tmi.ex

Connect to Twitch chat with Elixir.

The name is inspired by tmi.js.

Installation

The package can be installed by adding tmi to your list of dependencies in mix.exs:

def deps do
  [
    {:tmi, "~> 0.3.0"},
  ]
end

Documentation can be found at https://hexdocs.pm/tmi/readme.html.

Usage

You can use your own Twitch username, but it is recommended to make a new twitch account just for your bot. You'll also need an OAuth token for the password.

The simplest method to get an OAuth token (while logged in to the account your bot will use), use the Twitch Chat OAuth Password Generator.

Create a handler to deal with chat messages or events:

defmodule MyHandler do
  use TMI.Handler

  @impl true
  def handle_message("!" <> command, sender, chat) do
    case command do
      "dice" -> TMI.message(chat, Enum.random(~w(⚀ ⚁ ⚂ ⚃ ⚄ ⚅)))
      "echo " <> rest -> TMI.message(chat, rest)
      "dance" -> TMI.action(chat, "dances for #{sender}")
      _ -> TMI.message(chat, "unrecognized command")
    end
  end

  def handle_message(message, sender, chat) do
    Logger.debug("Message in #{chat} from #{sender}: #{message}")
  end
end

Available handler callbacks:

handle_connected(server, port)
handle_logged_in()
handle_login_failed(reason)
handle_disconnected()
handle_join(chat)
handle_join(chat, user)
handle_part(chat)
handle_part(chat, user)
handle_kick(chat, kicker)
handle_kick(chat, user, kicker)
handle_whisper(message, sender)
handle_message(message, sender, chat)
handle_mention(message, sender, chat)
handle_action(message, sender, chat)
handle_unrecognized(msg)

Starting

First we need to go over the config options.

Config options

Capabilities

Next, we can connect. Start TMI manually with:

config = [
  user: "mybotusername",
  pass: "oauth:mybotoauthtoken",
  chats: ["mychat"],
  handler: MyHandler,
  capabilities: [&#39;membership&#39;]
]

TMI.supervisor_start_link(config)

Or you can add it to your supervision tree, for example in MyApp.Application:

children = [
  {TMI.Supervisor, config}
]

The handler is for handling incoming messages, whispers, etc.

However, what if you want to interact?

TMI.message("mychat", "Hello World")

TMI.whisper("some_user", "Hey there")

TMI.action("mychat", "jumps around frantically")