Skip to content

Cookbook

Joshua Skelton edited this page Jul 10, 2018 · 14 revisions

Overview

Welcome to the Cookbook! Below you will find small examples/snippets (recipes) that are generally useful.

Table of Contents

Recipes

Voting

The vote bot will join a channel and call a vote. Votes can be cast for 60 seconds and then the result will be displayed. Votes can be changed, but will only be tallied once.

import time
from twitchobserver import Observer

votes = {}

def handle_event(event):
    if event.type != 'TWITCHCHATMESSAGE':
        return
        
    if event.message[0:2].upper() == '!Y':
        votes[event.nickname] = 1
        
    elif event.message[0:2].upper() == '!N':
        votes[event.nickname] = -1
        

observer = Observer('Nick', 'oauth:abcdefghijklmnopqrstuvwxyz0123')
observer.subscribe(handle_event)

observer.send_message('Voting has started!', 'channel')

observer.start()
observer.join_channel('channel')
time.sleep(60)
observer.unsubscribe(handle_event)

observer.send_message('Voting is over!', 'channel')

time.sleep(2)
tally = sum(votes.values())

if tally > 0:
    observer.send_message('The yeas have it!', 'channel')

elif tally < 0:
    observer.send_message('The nays have it!', 'channel')

else:
    observer.send_message('Its a draw!', 'channel')

observer.leave_channel('channel')
observer.stop()

Whisper Translator

The Whisper Translator bot will translate chat to your native language and whisper it to you. Note the example uses the Google Translate API which requires an account, but should be easily adaptable to any translation service.

import goslate
from twitchobserver import Observer

gs = goslate.Goslate()

nick = 'user_nick'
channel = 'channel'
native_lang_id = 'en'

with Observer('bot_nick', 'oauth:abcdefghijklmnopqrstuvwxyz0123') as observer:
    observer.join_channel(channel)

    while True:
        try:
            for event in observer.get_events():
                if event.type == 'TWITCHCHATMESSAGE' and event.nickname != observer._nickname and event.message:
                    language_id = gs.detect(event.message)

                    if language_id != native_lang_id:
                        translation = gs.translate(event.message, native_lang_id)
                        language_name = gs.get_languages()[language_id]

                        observer.send_whisper(nick, '{}({}): {}'.format(event.nickname, language_name, translation))

        except KeyboardInterrupt:
            observer.leave_channel(channel)

Information Displayer

With the Information Displayer Bot you can display random information at regular time intervals to all the users in a chat. Note: Make sure you do not hit Twitch's internal sending limit of 20 messages per 30 seconds.

import time
import random
from twitchobserver import Observer

# Define the messages to display.
messages = [
    "This is an example message to be displayed in chat.",
    "This is an example message that has an URL in it: https://github.com/JoshuaSkelly/twitch-observer/",
    "This is a very very very very very very very very very very very very very very very very very very very very very very very very very long message. Probably too long :)"
]

# Send a message every ten minutes.
messageSendInterval = 10 * 60

with Observer("nickname", "oauth:abcdefghijklmnopqrstuvwxyz0123") as observer:
    observer.join_channel("channel")

    while True:
        try:
            currentTime = time.time()

            if currentTime - lastTimeMessagedSend >= messageSendInterval:
                randomMessage = messages[random.randint(0, len(messages) - 1)]
                observer.send_message(randomMessage, "channel")

                lastTimeMessagedSend = currentTime
                
        except KeyboardInterrupt:
            observer.leave_channel("channel")
            break

Spam Filter

With the Spam Filter Bot you can timeout users that are probably writing in upper case.

from twitchobserver import Observer

with Observer("nickname", "oauth:abcdefghijklmnopqrstuvwxyz0123") as observer:
    observer.join_channel("channel")

    while True:
        try:
            for event in observer.get_events():
                if event.type == "TWITCHCHATMESSAGE":
                    # For every character in the message check if its an upper case
                    if len(event.message) <= 6:
                        continue

                    upperCaseCount = 0
                    for character in event.message:
                        if character.isalpha():
                            if character.isupper():
                                upperCaseCount += 1

                    if upperCaseCount / len(event.message) >= 0.75:
                        observer.send_message("{}. Please do not write in upper case!")
                        observer.timout_user(event.nickname, event.channel, 120)
                
        except KeyboardInterrupt:
            observer.leave_channel("channel")
            break

Using Decorators

As of version 0.8.0 it is now possible to use the decorator pattern to handle events.

from twitchobserver import Observer, ChatEventType

observer = Observer("nickname", "oauth:abcdefghijklmnopqrstuvwxyz0123")

@observer.on_command(ChatEventType.TWITCHCHATMESSAGE)
def handle_message(event):
    print(event.nickname, event.message)

observer.join_channel("channel")
observer.start()

# Wait

observer.stop()
Clone this wiki locally